Rust 无法将“*self”作为可变项借用,因为它也是作为不可变项借用的

Rust 无法将“*self”作为可变项借用,因为它也是作为不可变项借用的,rust,Rust,我希望我的struct函数在特殊条件下调用自己。当我将HashMap作为字段之一时,它工作正常,但当我将HashMap更改为Vec时,它就坏了。它甚至不需要被使用,这看起来很奇怪,我找不到任何合理的解释 use std::vec::Vec; use std::collections::HashMap; struct Foo<'a> { bar: Vec<&'a str> //bar: HashMap<&'a str, &'a

我希望我的struct函数在特殊条件下调用自己。当我将
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);
}
使用std::vec::vec;
使用std::collections::HashMap;
结构Foo
//条形图:HashMap
}
恳求{
pub fn new()->Foo选项{
没有一个
}
pub fn qux(&'a mut self,retry:bool){
设opt=self.baz();
如果重试{self.qux(false);}
}
}
pub fn main(){
让mut-foo=foo::new();
foo.qux(真);
}
游戏围栏:

错误:

<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         }

我想我找到了原因。这是
HashMap
定义:

pub struct HashMap<K, V, H = RandomSipHasher> {
    // All hashes are keyed on these values, to prevent hash collision attacks.
    hasher: H,

    table: RawTable<K, V>,

    // We keep this at the end since it might as well have tail padding.
    resize_policy: DefaultResizePolicy,
}
pub struct Vec<T> {
    ptr: *mut T,
    len: uint,
    cap: uint,
}
唯一的区别是类型参数的使用方式。现在让我们检查以下代码:

struct S1<T> { s: Option<T> }
//struct S1<T> { s: *mut T }

struct Foo<'a> {
    bar: S1<&'a str>
}

impl<'a> Foo<'a> {
    pub fn new() -> Foo<'a> {  // '
        Foo { bar: S1 { s: None } }
        //Foo { bar: S1 { s: std::ptr::null_mut() } }
    }

    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);
}
structs1{s:Option}
//结构S1{s:*mut T}
结构Foo
}
恳求{

pub fn new()->foo删除方法
baz()
定义中的
'a
。但不知道为什么会导致它。