我一直在用Rust编写一个简单的词法分析器。然而,我遇到了“错误[E0502]: 无法将'a_rule'借用为不可变的,因为它也被作为可变的借用
”问题。我查看了其他答案,但似乎找不到原因。
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
我也想借此机会问一下,是否建议使用像Java中的get和set方法,还是将结构体中的成员设置为public。
请随意指出任何其他愚蠢的错误。
'a
,而一个新的生命周期就足够了,这是一个常见的错误。我认为这是链接方法中self和引用的生命周期的重复,或者可能是从那里链接的其他问题之一。 - trent