rust - 借用检查器不会让我在调用 setter 后调用 getter

标签 rust immutability

<分区>

我一直在用 Rust 开发一个简单的词法分析器。但是,我遇到了 error[E0502]: cannot borrow 'a_rule' as immutable because it is also borrowed as mutable 问题。我检查了其他答案,但似乎找不到原因。

pub struct Rule<'a> {
    selector: &'a str,
}

impl<'a> Rule<'a> {
    pub fn new(selector: &'a str) -> Self {
        Self {
            selector
        }
    }

    pub fn get_selector(&'a self) -> &'a str {
        self.selector
    }

    pub fn set_selector(&'a mut self, selector: &'a str) {
        self.selector = selector
    }
}

#[cfg(test)]
mod tests {
    use super::Rule;

    #[test]
    fn set_selector_test() {
        let mut a_rule = Rule::new(".foo");
        a_rule.set_selector(".bar");

        assert_eq!(a_rule.get_selector(), ".bar")
    }
}

错误:

error[E0502]: cannot borrow `a_rule` as immutable because it is also borrowed as mutable
  --> src/lib.rs:30:20
   |
28 |         a_rule.set_selector(".bar");
   |         ------ mutable borrow occurs here
29 | 
30 |         assert_eq!(a_rule.get_selector(), ".bar")
   |                    ^^^^^^
   |                    |
   |                    immutable borrow occurs here
   |                    mutable borrow later used here

( Playground )

我还想借此机会询问是否建议使用 java 类似 get 和 set 方法,或者只是将结构中的成员设置为公共(public)。

请随时指出任何其他愚蠢的错误。

最佳答案

通过使 get_selectorset_selector 采用 &'a self/,您已将规则的生命周期与字符串的生命周期联系起来&'a mut self,但这不是它们之间的正确关系。你可以生成 &'a str 而不需要你的 self 活那么久(或者被可变地借用那么久)因为 self.selector已经是一个 &'a str

删除 self 引用上的 'a:

pub fn get_selector(&self) -> &'a str {
    self.selector
}

pub fn set_selector(&mut self, selector: &'a str) {
    self.selector = selector;
}

(但是你真的需要这个 getter 和 setter 吗?考虑不可变性!)

关于rust - 借用检查器不会让我在调用 setter 后调用 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61121260/

相关文章:

rust - 我不明白错误 E0508

rust - 类型提示中 _ 的正确术语是什么?

java - scala 计算读取文件中包含的列表中的字符串

python - Python 缺少 frozen-dict 类型的解决方法?

java - 创建不可变类时,集合是否应该只包含不可变对象(immutable对象)?

rust - 轮询时延迟 future 返回错误(关闭)

rust - 使用函数指针时为 "Expected fn item, found a different fn item"

rust - 当我想将所有权传递给函数时,调用采用引用的异步 Rust 函数的惯用方法

java - 为什么变量索引与 0x1f 进行两次 AND 运算?

rust - 我如何安全地使用可变借用的对象?