简体   繁体   English

Rust:为什么在struct内部借用引用会借用整个struct?

[英]Rust: why does borrowing a reference inside struct borrow the whole struct?

I have the following code:我有以下代码:

struct MyStruct<'a>{
    data: &'a str,
}

fn get<'a>(S: &'a MyStruct<'a>) -> &'a str{
    S.data
}

fn set<'a>(S: &'a mut MyStruct<'a>, x: &'a str){
    S.data = x;
}

fn main(){
    let mut S = MyStruct{data: "hello"};
    let foo: &str = get(&S);
    set(&mut S, "goodbye");
    dbg!(foo);
}

This fails to compile because let bar: &str = get(&S) takes an immutable borrow of S, and on the next line we take a mutable borrow.编译失败是因为let bar: &str = get(&S)对 S 进行了不可变借用,而在下一行我们进行了可变借用。 But we didn't borrow the whole Struct S, just the reference inside the struct.但是我们并没有借用整个Struct S,只是借用了struct内部的引用。 Why is the borrow still active?为什么借用仍然有效?

I think it has something to do with the lifetime annotations in get and set.我觉得跟get和set中的lifetime annotations有关系。 Those functions are my attempt to "desugar" how the corresponding member functions would look like.这些函数是我尝试“脱糖”的相应成员函数的样子。 If I change the signature of get to fn get<'a, 'b>(S: &'a MyStruct<'b>) -> &'b str , the code compiles.如果我将get的签名更改为fn get<'a, 'b>(S: &'a MyStruct<'b>) -> &'b str ,代码将编译。 Why does the signature affect the duration of the borrow?为什么签名会影响借用的期限?

By specifying the lifetime in get() to be fn(&'a MyStruct<'a>) -> &'a str , you say you're borrowing the whole struct for the lifetime of the string.通过将get()中的生命周期指定为fn(&'a MyStruct<'a>) -> &'a str ,您说您在字符串的生命周期内借用了整个结构。 Because the string is used after the set() , that time period includes the set() .因为字符串在set()之后使用,所以该时间段包括set() Thus, during the set() the struct is borrowed, which is an error.因此,在set()期间,结构被借用,这是一个错误。

If, on the other hand, you specify it to be fn(&'b MyStruct<'a>) -> &'a str , you borrow the struct only for the get() , and return the string inside with a different lifetime.另一方面,如果您将其指定为fn(&'b MyStruct<'a>) -> &'a str ,则您仅为get()借用该结构,并以不同的生命周期返回内部字符串.

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

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