我正在try 在Rust中创建一个简单的XML编写器,首先在内存中构建一个标签树.
在下面的函数add_child
中,我希望将新创建的子元素添加到当前元素的子元素列表中,然后返回该子元素,以便调用者可以将其他子元素添加到该子元素中.但我不能,因为这样子元素就归载体所有了.
在Rust中做这类事情的"惯用"方式是什么?
我想我可以让我的tag.rs
库的消费者自己操作 struct 中的子列表,但是实现细节并没有整齐地包含在函数中.
有没有其他更好的方法来做到这一点?
// 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);
}
}