循环变量之前的`&`的作用是什么? [英] What is the purpose of `&` before the loop variable?

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

问题描述

列表中的代码& i中的& 的目的是什么?如果删除& ,则会在 largest = i 中产生错误,因为它们的类型不匹配(其中 i &; 32 i i32 ).但是& i 如何将 i 转换为 i32 ?

What is the purpose of & in the code &i in list? If I remove the &, it produces an error in largest = i, since they have mismatched types (where i is &32 and i is i32). But how does &i convert i into i32?

fn largest(list: &[i32]) -> i32 {
    println!("{:?}", list);
    let mut largest = list[0];
    for &i in list {
        if i > largest {
            largest = i;
        }
    }
    largest
}

fn main() {
    let hey = vec![1, 3, 2, 6, 90, 67, 788, 12, 34, 54, 32];
    println!("The largest number is: {}", largest(&hey));
}

游乐场>

似乎在某种程度上取消了引用,但是为什么在下面的代码中,它不起作用?

It seems like it is somehow dereferencing, but then why in the below code, is it not working?

fn main() {
    let mut hey: i32 = 32;
    let x: i32 = 2;
    hey = &&x;
}

它说:

4 |     hey = &&x;
  |           ^^^ expected i32, found &&i32
  |
  = note: expected type `i32`
             found type `&&i32`

推荐答案

因此,通常当您对列表中的i使用时,循环变量 i 的类型为& i32 .

So normally when you use for i in list, the loop variable i would be of type &i32.

但是,当您使用表示列表中的& i时,您并没有取消引用,而是使用了模式匹配来显式地分解引用,这将使 i 的类型为 i32 .

But when instead you use for &i in list, you are not dereferencing anything, but instead you are using pattern matching to explicitly destructure the reference and that will make i just be of type i32.

请参阅Rust文档,以了解for-loop循环变量成为模式参考模式,我们在这里使用.另请参见解构指针.

See the Rust docs about the for-loop loop variable being a pattern and the reference pattern that we are using here. See also the Rust By Example chapter on destructuring pointers.

 

解决此问题的另一种方法是将 i 保持不变,然后将 i 与对 large 的引用进行比较,然后在分配给最大之前先取消引用 i :

An other way to solve this, would be to just keep i as it is and then comparing i to a reference to largest, and then dereferencing i before assigning to largest:

fn largest(list: &[i32]) -> i32 {
    println!("{:?}", list);
    let mut largest = list[0];
    for i in list {
        if i > &largest {
            largest = *i;
        }
    }
    largest
}

 

fn main() {
    let mut hey: i32 = 32;
    let x: i32 = 2;
    hey = &&x;
}

这根本行不通,因为在这里,您要为 i32 分配 hey ,以引用对 i32 的引用.代码>.这与循环变量情况下的模式匹配和解构无关.

This simply doesn't work, because here you are assigning hey, which is an i32, to a reference to a reference to an i32. This is quite unrelated to the pattern matching and destructuring in the loop variable case.

这篇关于循环变量之前的`&`的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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