为了更好地了解Rust,我正在构建一个简单的文本编辑器,并拥有以下结构体:
为了更好地了解Rust,我正在构建一个简单的文本编辑器,并拥有以下结构体:
struct File {
rows: Vec<Row>,
filename: Option<String>
}
impl File {
fn row(&self, index: u16) -> &Row{
&self.rows[index as usize]
}
}
struct Row {
string: String,
}
struct EditorState {
file: File,
}
正如您所看到的,我正在使用一个结构体来保存编辑器的状态,该结构体引用包含若干行的文件,每个行都包含一个字符串(这些结构体还有更多字段,但我已经移除了与问题无关的字段)。
现在我想让我的行可编辑,因此添加了以下内容:
impl Row {
fn insert(&mut self, at: u16, c: char) {
let at = at as usize;
if at >= self.string.len() {
self.string.push(c);
} else {
self.string.insert(at, c)
}
}
}
这是我尝试更新行的方式:
//In the actual functon, I am capturing the keypress,
//get the correct row from the state and pass it and the pressed
// char to row.insert
fn update_row(mut state: &mut EditorState) {
let row = &state.file.row(0);
row.insert(0, 'a');
}
这个无法编译:
error[E0596]: cannot borrow `*row` as mutable, as it is behind a `&` reference
从这个错误中,我可以看出问题在于 Row 应该是可变的,以便我可以编辑它(这很合理,因为我正在改变它的字符串)。 我无法弄清楚 a)如何能够在此处改变字符串,以及 b)如何在不使 row
总是返回可变引用的情况下实现此目标,因为在所有其他情况下,我都是调用 row
来读取一行,而不是写入。
&mut &Row
,这并没有真正帮助到你。 - fjhrow()
函数只返回一个只读引用,所以你不能使用该引用来修改行。你需要添加一个row_mut()
函数来返回可变引用。 - Sven Marnach