[英]Why does &v[1] + &v[2] have the same result as v[1] + v[2] in Rust?
I'm learning about ownership and borrowing. 我正在学习所有权和借款。
The difference between borrow1
and borrow2
is the usage of &
while printing in borrow2
: 之间的差borrow1
和borrow2
是的使用&
而在打印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]);
}
Why do they give the same output, even though borrow1
doesn't have &
? 为什么即使borrow1
没有&
,它们也给出相同的输出?
The index operator ( []
) for a Vec<T>
returns a T
. Vec<T>
的索引运算符( []
)返回T
In this case, that's an i32
. 在这种情况下,这就是i32
。 Thus v[0]
returns an i32
and &v[0]
returns an &i32
: 因此, v[0]
返回一个i32
, &v[0]
返回一个&i32
:
let a: i32 = v[0];
let b: &i32 = &v[0];
v[0]
only works because i32
implements Copy
. v[0]
仅适用于i32
实现Copy
。
i32
has implemented Add
for both the (left-hand side, right-hand-side) pairs of ( i32
, i32
) and ( &i32
, &i32
) . i32
为( i32
, i32
)和( &i32
, &i32
)的(左侧,右侧)对都实现了Add
。 The two implementations add values in the same way, so you get the same result. 这两种实现以相同的方式添加值,因此您将获得相同的结果。
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.