What is the exact definition of the for loop in Rust?

后端 未结 2 1561
轻奢々
轻奢々 2020-12-20 19:33

I\'m coming from a C (and to a lesser extent, C++) background. I wrote the following code snippet:

fn main() {
    let my_array = [1, 2, 3];
    let print_me         


        
2条回答
  •  攒了一身酷
    2020-12-20 19:37

    First of all, here's a link to the definition of for in the reference.

    To summarise, B is any expression which evaluates to something that can be converted into a value that implements the Iterator trait, whilst A is a irrefutable pattern that binds values of type T.

    In your specific case, slice::iter returns an Iter, which implements Iterator. That is, it doesn't yield i32s, it yields &i32s.

    Thus, in both the first and second examples, k is actually binding to &i32s, not i32s. When you specified the type of the closure, you were actually specifying the wrong type. The reason the final example works is because A is a pattern, not a variable name. What &k is actually doing is "de-structuring" the &i32, binding the i32 part to a variable named k.

    The "irrefutable" part simply means that the pattern must always work. For example, you can't do for Some(x) in thingy where thingy implements Iterator>; Some(x) would not necessarily be valid for every element in the iterator; thus, it's a refutable pattern.

提交回复
热议问题