Vec Box Error Indexing

I played with the structure Vecand came across some interesting bugs and behaviors that I cannot understand. Consider the following code .

fn main() {
    let v = vec![box 1i];
    let f = v[0];
}

When evaluating a rust in a code, the code causes the following errors:

<anon>:3:13: 3:17 error: cannot move out of dereference (dereference is implicit, due to indexing)
<anon>:3     let f = v[0];
                     ^~~~
<anon>:3:9: 3:10 note: attempting to move value to here (to prevent the move, use `ref f` or `ref mut f` to capture value by reference)
<anon>:3     let f = v[0];
                 ^
error: aborting due to previous error
playpen: application terminated with error code 101
Program ended.

My understanding of the method Vec indexis that it returns references to values ​​in Vec, so I don’t know t understand what is happening or implicit casts.

Also, when I change the variable fto underline , as shown below, no errors occur!

fn main() {
    let v = vec![box 1i];
    let _ = v[0];
}

I was hoping that someone would be able to explain the errors I get and why they go away when switching fto _.

+4
source share
3

, v[0] , .

.index(), :

fn main() {
    let v = vec![box 1i];
    let f = v.index(&0);
    println!("{}", f);
}

, , , .

EDIT:

Desugar v[0] - *v.index(&0) (from: https://github.com/rust-lang/rust/blob/fb72c4767fa423649feeb197b50385c1fa0a6fd5/src/librustc/middle/trans/expr.rs#L467).

fn main() { 
    let a = vec!(1i);
    let b = a[0] == *a.index(&0);
    println!("{}" , b);
}

true
+2

let f = v[0]; f ( , ): v[0] f. v[0] box, , , :

let a = box 1i;
let b = a;
// a cannot be used anymore, it has been moved
// following line would not compile
println!("{}", a);

, .

_, :

fn main() {
    let v = vec![box 1i];
    let _ = v[0];
    println!("{}", _);
}

:

<anon>:4:20: 4:21 error: unexpected token: `_`
<anon>:4     println!("{}", _);
                            ^

_ - , , , , -.

+1

, v [0]:

fn main() {
    let v = vec![box 1i];
    let f = &v[0]; // notice the &
    println!("{}",f);
}

, . , , ( ). :

fn main() {
    let v = vec![box 1i];
    let _ = &v[0];
    println!("{}",_);
}

:

<anon>:4:19: 4:20 error: unexpected token: `_`
<anon>:4     println!("{}",_);

(, , some_var , , _some_var ). , :

fn main() {
    let v = vec![box 1i];
    let f = &v[0];
    match **f {
        3i => println!("{}",f),
        _ => println!("nothing here")
    };
}

- , . , , .

+1
source

All Articles