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

问题描述 投票:0回答: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);
    }
}
rust ownership
1个回答
0
投票

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

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()
}
© www.soinside.com 2019 - 2024. All rights reserved.