因为它同时被借用为不可变的,所以无法将 `*self` 借用为可变的。

7
我希望我的结构体函数在特定条件下能够调用自身。当其中一个字段是 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
1个回答

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

这是Vec的定义:

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

这个可以编译。如果你选择了另一个使用*mut T指针的S1定义,那么程序就会出现这个错误。

看起来像是一个生命周期变异的 bug。

更新:这里提交了它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接