当用作 for 循环变量时,`e1` 和 `&e2` 之间有什么区别? [英] What is the difference between `e1` and `&e2` when used as the for-loop variable?

查看:59
本文介绍了当用作 for 循环变量时,`e1` 和 `&e2` 之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器说e1: &i32e2: i32.阅读文档 slice::Iter关于循环的书籍章节,我还是一头雾水.

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.

更一般地说,切片中的特定元素可以被拥有吗?在情况 2 中,e2 似乎拥有一个元素,是吗?

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
    }
}

推荐答案

解构模式绑定中使用时,与符号 & 用于取消引用一个值:

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`

这适用于接受模式的任何地方,例如在 letif let 中,作为函数参数、for 循环变量或匹配臂.

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`
}

注意 val 是如何不再被 Some包裹"的,就像它不再被引用包裹"一样.

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

& 在模式中的这种行为就是需要 ref 关键字的原因.ref 关键字用于在模式匹配中明确引入一个引用.

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.

这篇关于当用作 for 循环变量时,`e1` 和 `&amp;e2` 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆