返回对自身的引用的函数无法编译,而相同的代码可以
Function returning reference to self can't compile, while the same code can
给定两个片段,它们试图 return 从 self 引用一个成员值,我真的不明白为什么带有单独函数的那个不能编译。
这个有效(godbolt):
struct Foo {
a: bool,
b: u32,
}
impl Foo {
fn get(&mut self) -> &u32 {
if self.a {
return &self.b;
}
self.a = true;
self.b = 10;
return &self.b;
}
}
虽然这不是 (godbolt):
struct Foo {
a: bool,
b: u32,
}
impl Foo {
fn try_get(&self) -> Option<&u32> {
if self.a {
return Some(&self.b);
}
return None;
}
fn get(&mut self) -> &u32 {
if let Some(val) = self.try_get() {
return val;
}
self.a = true;
self.b = 10;
return &self.b;
}
}
错误:
error[E0506]: cannot assign to `self.a` because it is borrowed
--> src/lib.rs:19:9
|
14 | fn get(&mut self) -> &u32 {
| - let's call the lifetime of this reference `'1`
15 | if let Some(val) = self.try_get() {
| -------------- borrow of `self.a` occurs here
16 | return val;
| --- returning this value requires that `*self` is borrowed for `'1`
...
19 | self.a = true;
| ^^^^^^^^^^^^^ assignment to borrowed `self.a` occurs here
据我了解,它看不到顶部的引用会在可变更改之前释放,但为什么呢?不用函数也能证明,为什么不能用?
有什么方法可以使函数调用起作用吗?
对我来说这真的像是一个错误
之前没有看到类似的答案,但是编辑Whosebug后发现:
TLDR:是的,这是一个已知错误,将被修复,在这样的实现中没有(有用的)方法来使用函数
https://github.com/rust-lang/rust/issues/21906#issuecomment-73296543
给定两个片段,它们试图 return 从 self 引用一个成员值,我真的不明白为什么带有单独函数的那个不能编译。
这个有效(godbolt):
struct Foo {
a: bool,
b: u32,
}
impl Foo {
fn get(&mut self) -> &u32 {
if self.a {
return &self.b;
}
self.a = true;
self.b = 10;
return &self.b;
}
}
虽然这不是 (godbolt):
struct Foo {
a: bool,
b: u32,
}
impl Foo {
fn try_get(&self) -> Option<&u32> {
if self.a {
return Some(&self.b);
}
return None;
}
fn get(&mut self) -> &u32 {
if let Some(val) = self.try_get() {
return val;
}
self.a = true;
self.b = 10;
return &self.b;
}
}
错误:
error[E0506]: cannot assign to `self.a` because it is borrowed
--> src/lib.rs:19:9
|
14 | fn get(&mut self) -> &u32 {
| - let's call the lifetime of this reference `'1`
15 | if let Some(val) = self.try_get() {
| -------------- borrow of `self.a` occurs here
16 | return val;
| --- returning this value requires that `*self` is borrowed for `'1`
...
19 | self.a = true;
| ^^^^^^^^^^^^^ assignment to borrowed `self.a` occurs here
据我了解,它看不到顶部的引用会在可变更改之前释放,但为什么呢?不用函数也能证明,为什么不能用?
有什么方法可以使函数调用起作用吗?
对我来说这真的像是一个错误
之前没有看到类似的答案,但是编辑Whosebug后发现:
TLDR:是的,这是一个已知错误,将被修复,在这样的实现中没有(有用的)方法来使用函数
https://github.com/rust-lang/rust/issues/21906#issuecomment-73296543