英文:
Rust: Mutable references to each element of a tuple possible at the same time
问题
以下代码可以正常编译,没有任何问题:
fn main() {
let mut w = (107, 109);
let w0 = &mut w.0;
let w1 = &mut w.1;
*w0 = 110;
*w1 = 111;
println!("{}", w0);
println!("{}", w1);
println!("{:?}", w);
}
但是下面的代码无法编译,因为现在 w
是一个数组:
fn main() {
let mut w = [107, 109];
let w0 = &mut w[0];
let w1 = &mut w[1];
*w0 = 110;
*w1 = 111;
println!("{}", w0);
println!("{}", w1);
println!("{:?}", w);
}
为什么这个情况下它适用于元组?
英文:
Below code compiles without any issues:
fn main() {
let mut w = (107, 109);
let w0 = &mut w.0;
let w1 = &mut w.1;
*w0 = 110;
*w1 = 111;
println!("{}", w0);
println!("{}", w1);
println!("{:?}", w);
}
But the following doesn't compile where w is now an array:
fn main() {
let mut w = [107, 109];
let w0 = &mut w[0];
let w1 = &mut w[1];
*w0 = 110;
*w1 = 111;
println!("{}", w0);
println!("{}", w1);
println!("{:?}", w);
}
Why is it the case that it works with tuples?
答案1
得分: 4
> 为什么它可以用于元组?
元组是一个匿名结构,即使字段是按位置命名的。因此,编译器理解 w.0
和 w.1
不会重叠,并且能够分离借用。
然而,数组是索引的,对编译器而言是不透明的,因此 w[0]
和 w[1]
可能是同一个位置。
英文:
> Why is it the case that it works with tuples?
A tuple is an anonymous structure, even if the fields are named by their position. So the compiler understands that w.0
and w.1
don't overlap and it's able to split the borrow.
Arrays however are indexed, they are opaque to the compiler, for which w[0]
and w[1]
may well be the same location.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论