我希望我的结构体函数在特定条件下能够调用自身。当其中一个字段是
HashMap
时,它可以工作,但是当我将 HashMap
更改为 Vec
时,它就出现了问题。即使不使用它,这似乎非常奇怪,我找不到任何合理的解释。use std::vec::Vec;
use std::collections::HashMap;
struct Foo<'a> {
bar: Vec<&'a str>
//bar: HashMap<&'a str, &'a str>
}
impl<'a> Foo<'a> {
pub fn new() -> Foo<'a> {
Foo { bar: Vec::new() }
//Foo { bar: HashMap::new() }
}
pub fn baz(&'a self) -> Option<int> {
None
}
pub fn qux(&'a mut self, retry: bool) {
let opt = self.baz();
if retry { self.qux(false); }
}
}
pub fn main() {
let mut foo = Foo::new();
foo.qux(true);
}
playpen: http://is.gd/GgMy79
错误:
<anon>:22:24: 22:28 error: cannot borrow `*self` as mutable because it is also borrowed as immutable
<anon>:22 if retry { self.qux(false); }
^~~~
<anon>:21:23: 21:27 note: previous borrow of `*self` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `*self` until the borrow ends
<anon>:21 let opt = self.baz();
^~~~
<anon>:23:10: 23:10 note: previous borrow ends here
<anon>:20 pub fn qux(&'a mut self, retry: bool) {
<anon>:21 let opt = self.baz();
<anon>:22 if retry { self.qux(false); }
<anon>:23 }
我该如何解决这个问题?这可能是由于#6268引起的吗?
baz()
的定义中,删除'a
。虽然不知道为什么会导致问题。 - Levans