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

时间:2014-11-14 20:18:00

标签: 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 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);
}

围栏: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造成的吗?

1 个答案:

答案 0 :(得分:4)

我想我找到了原因。这是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);
}

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

这看起来像一个错误,我想是在生命变异的某个地方。

更新已提交here