【问题标题】:Why can I call a function that accepts a reference with a reference of a reference?为什么我可以用引用的引用来调用接受引用的函数?
【发布时间】:2016-11-11 22:15:11
【问题描述】:

据我所知,& 符号创建了一个引用。但是使用sum_vec 或不使用& 都可以编译。我只想知道当我做let s1 = sum_vec(&v1); 时发生了什么。这会创建引用的引用吗?

fn main() {
    // Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed.
    fn sum_vec(v: &Vec<i32>) -> i32 {
        return v.iter().fold(0, |a, &b| a + b);
    }
    // Borrow two vectors and sum them.
    // This kind of borrowing does not allow mutation to the borrowed.
    fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
        // do stuff with v1 and v2
        let s1 = sum_vec(v1);//This wil also complile with &. Is this optional?.
        let s2 = sum_vec(v2);
        // return the answer
        s1 + s2
    }

    let v1 = vec![1, 2, 3];
    let v2 = vec![4, 5, 6];

    let answer = foo(&v1, &v2);
    println!("{}", answer);
    println!("{}", v1.len());
}

(playground)

【问题讨论】:

  • 注意:采用&amp;[T] 参数而不是&amp;Vec&lt;T&gt; 参数更习惯用法(也更灵活)。 Vec 和 slice 之间的唯一区别是后者在可变时允许添加/删除元素。因为当不可变时没有区别,使用最小公分母允许更多代码调用函数。
  • @MatthieuM。就像我们made a question,所以我们不必一直重复这个^_^
  • 为什么不喜欢?
  • @CodeJoy:StackOverflow 之谜;不要太担心一票。

标签: rust


【解决方案1】:

是和否。Rust 将创建对引用的引用(因为您使用 &amp; 运算符明确要求它),然后立即再次“自动删除”它以适应目标类型。然后优化器将消除该中间引用。

【讨论】:

  • Clippy 会警告你你输入了一些愚蠢的东西。
猜你喜欢
  • 2015-10-08
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 2016-03-05
  • 2014-03-30
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
相关资源
最近更新 更多