简体   繁体   English

如何修改 Rust 中借用结构的字段?

[英]How do I modify a borrowed struct's field in Rust?

I have a &mut reference to a struct.我有一个对结构的&mut引用。 I want to reassign a field of the referenced struct, but I only get cannot assign to current_node.parameter because it is borrowed .我想重新分配引用结构的一个字段,但我只能得到cannot assign to current_node.parameter because it is borrowed

I have also tried let ref mut in the current_node declaration, but the same issue happened.我也尝试在current_node声明中使用let ref mut ,但同样的问题发生了。

pub fn create_ars_tree() {
    let mut top_level_node = NodeItem {
        key: StringOrNodeItems::Text(String::new()),
        parameter: StringOrNodeItems::Text(String::new()),
        parent_item: None,
    };
    let mut current_node = &mut top_level_node; //Reference to the currently edited node
    let mut current_part = &current_node.key; //Reference to the currently edited string
    for current_char in "abcdef".chars() {
        if current_char == '{' {
            //Handle new opening bracket
            match current_part {
                StringOrNodeItems::Text(text) => {
                    current_node.key = StringOrNodeItems::Keys(vec![
                        NodeItem {
                            key: StringOrNodeItems::Text(text.to_string()),
                            parameter: StringOrNodeItems::Text(String::new()),
                            parent_item: Some(current_node)
                            //parent_item: None
                        }
                    ]);
                },
                StringOrNodeItems::Keys(keys) => {
                    unimplemented!();
                }
            }
        }
    }
}

#[derive(Debug)]
pub struct NodeItem<'a> {
    key: StringOrNodeItems<'a>,
    parameter: StringOrNodeItems<'a>,
    parent_item: Option<&'a NodeItem<'a>>,
}

#[derive(Debug)]
enum StringOrNodeItems<'a> {
    Text(String),
    Keys(Vec<NodeItem<'a>>),
}

Error:错误:

error[E0506]: cannot assign to `current_node.key` because it is borrowed
  --> src/lib.rs:14:6
   |
8  |     let mut current_part = &current_node.key; //Reference to the currently edited string
   |                            ----------------- borrow of `current_node.key` occurs here
...
12 |             match current_part {
   |                   ------------ borrow later used here
13 |                 StringOrNodeItems::Text(text) => {
14 |                     current_node.key = StringOrNodeItems::Keys(vec![
   |                     ^^^^^^^^^^^^^^^^ assignment to borrowed `current_node.key` occurs here

Playground 操场

I have figured it out.我已经想通了。 The issue is that I am trying to assign current_node inside a block borrowing that same variable.问题是我试图在借用相同变量的块内分配current_node If you replace Some(current_node) with None it compiles如果将Some(current_node)替换为None它会编译

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM