Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

rust - What is the difference between `e1` and `&e2` when used as the for-loop variable?

The compiler says that e1: &i32 and e2: i32. Having read the docs for slice::Iter and the book chapter on loops, I'm still confused.

More generally, can a particular element in a slice be owned? It seems like in case 2, e2 is owning an element, is it?

fn main() {
    let slice = &[1, 2, 3];
    for e1 in slice.iter() {
        println!("{}", e1); // case 1
    }

    for &e2 in slice.iter() {
        println!("{}", e2); // case 2
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When used in a destructuring pattern binding, the ampersand & is used to dereference a value:

let a_number: i32 = 42;
let a_reference_to_a_number: &i32 = &a_number;

let another_reference = a_reference_to_a_number;
let &another_number = a_reference_to_a_number;

let () = another_reference; // expected type `&i32`
let () = another_number;    // expected type `i32`

This applies anywhere a pattern is accepted, such as in a let or if let, as a function argument, the for-loop variable, or a match arm.


While initially confusing to many people, this is actually the language being consistent with how enums and structs are pattern matched and thus removed from the inner variable binding:

let a_value: Option<&i32> = Some(&42);

if let Some(&val) = a_value {
    let () = val; // expected type `i32`
}

Note how val is no longer "wrapped" by the Some, just like it is no longer "wrapped" by the reference.

This behavior of & in patterns is why the ref keyword is needed. The ref keyword is used to unambiguously introduce a reference in a pattern match.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...