我正在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);
}
}