gpt4 book ai didi

rust - 在非词句生存期内,何时引用是 'used'?

转载 作者:行者123 更新时间:2023-12-03 11:41:45 25 4
gpt4 key购买 nike

struct Object {
alive: bool,
name: String,
}

impl Object {
// the comments are what I thought the compiler was supposed to give
fn test(&mut self) {
let alive = &mut self.alive; // seems like there is mutable borrow here
self.name = String::from("dead"); // another mutable borrow
*alive = false; // mutable borrow later used here
}
}

fn print(x: &Object) {
println!("Hello {:?}", x);
}
非词汇生存期应该是引用在上次使用后停止生存的时间。我对这种用途感到困惑。 alive是对 self.alive的可变借用,然后使用 self进行 self.name = String::from("dead");。此后,似乎再次在 *alive = false中使用了live。除非此代码编译。
如果我将代码更改为此:
    fn test(&mut self) {
let alive = &mut self.alive;
print(self);
self.name = String::from("dead");
*alive = false;
}
然后代码给出了这个错误
error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable                                                                 [10/58]
--> src/main.rs:45:15
|
44 | let alive = &mut self.alive;
| --------------- mutable borrow occurs here
45 | print(self);
| ^^^^ immutable borrow occurs here
46 | self.name = String::from("dead");
47 | *alive = false;
| -------------- mutable borrow later used here
。这是否意味着仅当引用在函数中时才被“使用”,而在用*或点符号取消引用时才被“使用”?即使引用范围重叠,第一个示例也如何编译?

最佳答案

Does this mean that references are only 'used' when they are in functions and not when dereferenced with * or the dot notation?


你近了。非词法生存期不是这里的因素,但是借位检查器有更多的技巧可以解决。它知道结构的字段是不同的对象,可以独立借用。
Splitting Borrows上的Rust Nomicon:

It does understand structs sufficiently to know that it's possible to borrow disjoint fields of a struct simultaneously. So this works today:

struct Foo {
a: i32,
b: i32,
c: i32,
}

let mut x = Foo {a: 0, b: 0, c: 0};
let a = &mut x.a;
let b = &mut x.b;
let c = &x.c;
*b += 1;
let c2 = &x.c;
*a += 10;
println!("{} {} {} {}", a, b, c, c2);

因此,在您的代码中,可以存在对 self.aliveself.name的互斥引用,因为借阅检查器知道它们未引用同一对象。添加 print(self)需要引用整个 self,并且与给 alive的借用冲突。

关于rust - 在非词句生存期内,何时引用是 'used'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com