不能借用 `*self` 作为可变的,因为它也被借用为不可变的

jgi*_*ich 7 rust

我希望我的 struct 函数在特殊条件下调用自己。当我将 aHashMap作为字段之一时它起作用,但是当我HashMap将 a更改为 a时它坏了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);
}
Run Code Online (Sandbox Code Playgroud)

围栏: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         }
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?这可能是由#6268引起的吗?

Vla*_*eev 6

我想我找到了原因。这是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,
}
Run Code Online (Sandbox Code Playgroud)

这是Vec定义:

pub struct Vec<T> {
    ptr: *mut T,
    len: uint,
    cap: uint,
}
Run Code Online (Sandbox Code Playgroud)

唯一的区别是如何使用类型参数。现在让我们检查一下这段代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

这个编译。如果您为S1, 使用*mut T指针选择另一个定义,则程序将失败并显示此错误。

我认为这看起来像是一个错误,在生命周期的某个地方。

更新在这里提交