简体   繁体   English

移动结构后,我对结构成员的引用如何仍然有效?

[英]How is my reference to a struct member still valid after the struct was moved?

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. 我正在使用函数(名为get )创建对结构成员的引用,然后使用另一个函数(名为pr )移动结构,然后我取消引用先前创建的指针。

Am I in the wrong here (aka 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);
}

The Rust playground outputs: Rust操场输出:

Hello, world!
MyStruct 3
i 3

The let expression gets pattern-matched and let表达式与模式匹配

let &i = get(&x); // i.e. a &i32

Results in i being assigned to i32 and since i32 is copyable, there is no ownership violation. i被分配到i32 ,因为i32是可复制的,所以没有所有权违规。

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 ). Rust引用声明“let语句引入了一组新的变量,由模式给出”( )和“模式由文字,结构化数组或枚举构造函数,结构和元组,变量绑定规范的某种组合组成”( 来源) )。

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. 绑定的左侧, &i不仅仅是一个文字,它告诉编译器它应该尝试与右侧表达式进行模式匹配。 In this case it results in i pointing to a copyable value ( i32 ) and not a reference ( &i32 ). 在这种情况下,它导致i指向可复制值( i32 )而不是引用( &i32 )。 In other words: 换一种说法:

let &i = get(&x);

is equivalent to 相当于

let i = *get(&x);

So x is not borrowed and pr(x) is still applicable. 所以x不是借用的, pr(x)仍然适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM