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