【发布时间】:2020-06-20 21:22:55
【问题描述】:
我开始学习 Rust,在实验过程中,我发现所有权应用于我不理解的元组和数组的方式有所不同。基本上,以下代码显示了区别:
#![allow(unused_variables)]
struct Inner {
in_a: u8,
in_b: u8
}
struct Outer1 {
a: [Inner; 2]
}
struct Outer2 {
a: (Inner, Inner)
}
fn test_ownership(num: &mut u8, inner: &Inner) {
}
fn main() {
let mut out1 = Outer1 {
a: [Inner {in_a: 1, in_b: 2}, Inner {in_a: 3, in_b: 4}]
};
let mut out2 = Outer2 {
a: (Inner {in_a: 1, in_b: 2}, Inner {in_a: 3, in_b: 4})
};
// This fails to compile
test_ownership(&mut out1.a[0].in_a, &out1.a[1]);
// But this works!
test_ownership(&mut out2.a.0.in_a, &out2.a.1);
}
test_ownership() 的第一次调用没有编译,正如预期的那样,Rust 发出一个错误,抱怨同时对 out1.a[_] 进行了可变和不可变引用。
error[E0502]: cannot borrow `out1.a[_]` as immutable because it is also borrowed as mutable
--> src/main.rs:27:41
|
27 | test_ownership(&mut out1.a[0].in_a, &out1.a[1]);
| -------------- ------------------- ^^^^^^^^^^ immutable borrow occurs here
| | |
| | mutable borrow occurs here
| mutable borrow later used by call
但我不明白的是,为什么第二次调用 test_ownership() 不会让借用检查器发疯?似乎数组被视为一个独立于被访问索引的整体,但元组允许对其不同索引进行多个可变引用。
【问题讨论】:
标签: rust