代码之家  ›  专栏  ›  技术社区  ›  mydoghasworms

如何将元素添加到向量中并返回对该元素的引用?

  •  1
  • mydoghasworms  · 技术社区  · 1 年前

    我正在Rust中尝试一个简单的XML编写器,首先在内存中构建一个标记树。

    在函数中 add_child 在下面,我想将新创建的子元素添加到当前元素的子元素列表中,然后返回该子元素,以便调用方可以向该子元素添加其他子元素。但我做不到,因为子对象被向量所拥有。

    在Rust中,做这种事情的“惯用”方式是什么?

    我想我可以让我的消费者 tag.rs 库本身操作结构中的子级列表,但实现细节并没有整齐地包含在函数中。

    还有其他更好的方法吗?

    // tag.rs
    use std::collections::HashMap;
    
    pub struct Tag<'a> {
        name: &'a str,
        attributes: HashMap<&'a str, &'a str>,
        children: Vec<Tag<'a>>,
    }
    
    impl<'a> Tag<'a> {
        pub fn new(name: &'a str) -> Self {
            Self {
                name,
                attributes: HashMap::new(),
                children: vec![],
            }
        }
    
        pub fn add_child(&mut self, name: &'a str) -> Self {
            let mut child = Self::new(name);
            self.children.push(child); // `child` moved here
            child // <-- Error: use of moved value: `child`        
        }
    
        pub fn add_attribute(&mut self, key: &'a str, value: &'a str) {
            self.attributes.insert(key, value);
        }
    }
    
    1 回复  |  直到 1 年前
        1
  •  2
  •   drewtato    1 年前

    您可以返回对最后一个元素的可变引用:

    pub fn add_child(&mut self, name: &'a str) -> &mut Self {
        let mut child = Self::new(name);
        self.children.push(child); // `child` moved here
        self.children.last_mut().unwrap()
    }