Rust vec动态数组的索引与借用

对于rust中的元素,可以是Copy类型和非Copy类型,从而导致在元素访问时存在不同的底层逻辑。
首先,对于vec[idx],返回的是引用&T
对于Copy类型:

    let mut ve=vec![1,2,3];
    let it=vec[1];//copy
    println!("{}", it32);

it的类型是int32而非&int32,因为:
vec[1]是a place expression,
let it=vec[1]; is evaluated in a value expression context
If the type of that value implements Copy, then the value will be copied.
所以i32会被copy给it
https://doc.rust-lang.org/reference/expressions.html

    let mut ve=vec![1,2,3];
    println!("{:#p}",vei32.as_ptr());
    let it32r = &vei32[0];//it32r 值为直接对vec第二个元素的借用
    println!("{:p}", it32r);
    //vei32.as_ptr()与it32r地址相同

it32r 值为直接对vec第二个元素的借用,原因:
The & (shared borrow) and &mut (mutable borrow) operators are unary prefix operators.
When applied to a place expression, this expressions produces a reference (pointer) to the location that the value refers to.
所以vei32[0]返回借用,&vei32[0]直接获取元素地址仍是借用。
https://doc.rust-lang.org/reference/expressions/operator-expr.html#borrow-operators

    let mut ve=vec![1,2,3];
    let it32r = &vei32[0];
    vei32.push(4);
    //报错:
    //cannot borrow `vei32` as mutable because it is also borrowed as immutable 
    //mutable borrow occurs here
    println!("{:p}", it32r);

原因分析:对于vec,vec[idx]相当于vecbuffer的切片,所以&vei32[0]虽然是对第一个元素的借用,但也是对整个buffer的借用,所以会导致vei32.push(4);报错。
对于非Copy类型:

    let mut vec=vec![
        String::from("a"),
        String::from("b"),
        String::from("c")
    ];
    let it = vec[1];
    //cannot move out of index of `Vec<String>`
    //move occurs because value has type `String`, which does not implement the `Copy` trait

所以对于非Copy类型元素,对索引需要借用:

    let mut vec=vec![
        String::from("a"),
        String::from("b"),
        String::from("c")
    ];
    let it = &vec[1];
    vec.push(String::from("value"));
    //cannot borrow `vec` as mutable because it is also borrowed as immutable
    //mutable borrow occurs here
    //同上
posted @ 2025-11-28 11:13  tristone95  阅读(14)  评论(0)    收藏  举报