【问题标题】:cannot borrow `*self` as mutable because it is also borrowed as immutable不能将 `*self` 借为可变的,因为它也被借为不可变的
【发布时间】:2014-11-14 20:18:00
【问题描述】:

我希望我的 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造成的?

【问题讨论】:

  • 删除方法baz()定义中的'a。不知道为什么会导致它。

标签: rust


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多