问题描述
我正在使用函数(名为 get
)创建对结构成员的引用,然后使用另一个函数(名为 pr
)移动结构,然后我取消引用之前创建的指针.
I'm creating a reference to a structure member using a function (named get
), then I move the struct using another function (named pr
), then I dereference the previously created pointer.
我在这里做错了吗(也就是意外工作),或者我的参考依据某些规则仍然有效?
Am I in the wrong here (a.k.a. working by accident), or is my reference is still valid by some rule?
struct MyStruct {
inner: i32,
}
fn get(a: &MyStruct) -> &i32 {
return &a.inner;
}
fn pr(a: MyStruct) {
println!("MyStruct {}", a.inner);
}
fn main() {
println!("Hello, world!");
let x = MyStruct { inner: 3 };
let &i = get(&x);
pr(x);
println!("i {}", i);
}
Rust 游乐场 输出:
Hello, world!
MyStruct 3
i 3
推荐答案
let
表达式得到模式匹配和
The let
expression gets pattern-matched and
let &i = get(&x); // i.e. a &i32
导致 i
被分配给 i32
并且由于 i32
是可复制的,所以不存在所有权冲突.
Results in i
being assigned to i32
and since i32
is copyable, there is no ownership violation.
Rust 参考声明一个 let 语句引入了一组由模式给出的新变量"(source) 和模式由文字、解构数组或枚举构造函数、结构和元组、变量绑定规范的某种组合组成"(来源).
The Rust reference states that "a let statement introduces a new set of variables, given by a pattern" (source) and "patterns consist of some combination of literals, destructured arrays or enum constructors, structs and tuples, variable binding specifications" (source).
绑定的左侧,&i
不仅仅是一个文字,它告诉编译器它应该尝试对右侧表达式进行模式匹配.在这种情况下,它导致 i
指向可复制值 (i32
) 而不是引用 (&i32
).换句话说:
The left-hand side of the binding, &i
is not just a literal, which tells the compiler that it should try to pattern-match against the right-hand side expression. In this case it results in i
pointing to a copyable value (i32
) and not a reference (&i32
). In other words:
let &i = get(&x);
相当于
let i = *get(&x);
所以 x
没有被借用,pr(x)
仍然适用.
So x
is not borrowed and pr(x)
is still applicable.
这篇关于移动结构后,我对结构成员的引用如何仍然有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!