我与借阅检查器有一个论点。我的问题稍微复杂一点,但是在这种情况下,我使用的是类似结构的缓冲区。我的缓冲区具有一个函数safe_write_to_slot
,该函数首先检索第一个空元素(返回Ok(位置)或Err(错误消息)的结果),然后将值写入该检索到的位置。但是问题是,当我将检索到的位置分配给一个值时,rust会抱怨我稍后再使用一次self。我如何首先调用一个返回结果的(self)函数,然后继续使用self做一些动作?
use std::result::Result;
struct Elems {
pub elems : Vec<int>,
}
impl Elems {
pub fn new() -> Elems {
Elems{elems: vec![0,0,0,0,0,0]}
}
pub fn safe_write_to_slot(&mut self, elem : uint) -> Result<(), &str> {
let loc = try!(self.get_slot());
self.unsafe_write_to_slot(loc);
Ok(())
}
pub fn get_slot(&self) -> Result<uint, &str>{
let mut loc = -1i;
for x in range(0, self.elems.len()) {
if *self.elems.get(x) == 0 {
loc = x as int;
}
}
if loc != -1 { Ok(loc as uint) } else { Err("No free slots") }
}
fn unsafe_write_to_slot(&mut self, elem : uint) {
self.elems[elem] = 1;
}
}
我得到的错误是:
Compiling borrow v0.0.1 (file:///borrow)
main.rs:19:9: 19:13 error: cannot borrow `*self` as mutable because it is also borrowed as immutable
main.rs:19 self.unsafe_write_to_slot(loc);
^~~~
main.rs:17:24: 17:28 note: previous borrow of `*self` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `*self` until the borrow ends
main.rs:17 let loc = try!(self.get_slot());
^~~~
/main.rs:17:19: 17:41 note: expansion site
main.rs:22:6: 22:6 note: previous borrow ends here
main.rs:16 pub fn safe_write_to_slot(&mut self, elem : uint) -> Result<(), &str> {
/main.rs:22 }
^
main.rs:37:9: 37:29 error: cannot assign to immutable dereference (dereference is implicit, due to indexing)
main.rs:37 self.elems[elem] = 1;
^~~~~~~~~~~~~~~~~~~~
error: aborting due to 2 previous errors
Could not compile `borrow`.
To learn more, run the command again with --verbose.
终生推断是导致此问题的原因。
该get_slot
方法解释为:
pub fn get_slot<'a>(&'a self) -> Result<uint, &'a str> {
结果与绑定到相同的生存期self
,这将导致self
冻结,直到删除结果为止。但是,您不希望将的生存期链接self
到&str
,因为您只返回字符串文字。通过更改&str
为&'static str
inget_slot
和safe_write_to_slot
,您将不再收到错误,因为self
在调用时将不再被认为是借来的unsafe_write_to_slot
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句