The difference between borrow1 and borrow2 is the usage of & while printing in borrow2:fn borrow1(v: &Vec<i32>) { println!("{}", &v[10] + &v[12]);}fn borrow2(v: &Vec<i32>) { println!("{}", v[10] + v[12]);}fn main() { let mut v = Vec::new(); for i in 1..1000 { v.push(i); } borrow1(&v); println!("still own v {} , {}", v[0], v[1]); borrow2(&v); println!("still own v {} , {}", v[0], v[1]);}为什么它们给出相同的输出,即使 borrow1 没有 &?Why do they give the same output, even though borrow1 doesn't have &?推荐答案Vec 的索引运算符 ([]) 返回一个 T.在这种情况下,这是一个 i32.因此 v[0] 返回一个 i32 而 &v[0] 返回一个 &i32:The index operator ([]) for a Vec<T> returns a T. In this case, that's an i32. Thus v[0] returns an i32 and &v[0] returns an &i32:let a: i32 = v[0];let b: &i32 = &v[0];v[0] 之所以有效,是因为 i32 实现了 复制.v[0] only works because i32 implements Copy.i32 已经为 (i32, i32) 和 (&i32, &i32).这两个实现以相同的方式添加值,所以你得到相同的结果.i32 has implemented Add for both the (left-hand side, right-hand-side) pairs of (i32, i32) and (&i32, &i32). The two implementations add values in the same way, so you get the same result.另见:切片索引操作的返回类型是什么?了解(自动?)在添加引用和数字值时取消引用/强制 这篇关于为什么 &amp;v[1] + &amp;v[2] 与 Rust 中的 v[1] + v[2] 具有相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-22 17:01