gpt4 book ai didi

rust - 在同一个函数中多次使用 self

转载 作者:行者123 更新时间:2023-11-29 08:05:38 24 4
gpt4 key购买 nike

我和借用检查员发生了争执。我的问题有点复杂,但对于这种情况,我使用的是类似缓冲区的结构。我的缓冲区有一个函数 safe_write_to_slot,它首先检索第一个空元素(返回 Ok(location) 或 Err(error message) 的结果),然后将值写入该检索到的位置。然而,问题是,当我将检索到的位置分配给一个值时,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> {

结果被绑定(bind)到与 self 相同的生命周期,这导致 self 保持卡住状态,直到结果被删除。但是,您不想将 self 的生命周期链接到 &str,因为您只返回字符串文字。通过在 get_slotsafe_write_to_slot 中将 &str 更改为 &'static str,您将不会再收到错误,因为 self 在调用 unsafe_write_to_slot 时将不再被认为是借用的。

关于rust - 在同一个函数中多次使用 self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27436021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com