I have a struct that keeps quick_xml::Writer
inside. In Writer
, there's a helper method that creates a struct, but the struct borrows Writer
itself. And I can't pass this struct in another method to reduce repetitions.
I tried returning the struct back, but since there are errors to propagate, it must be wrapped, and compiler wanted some weird return type, which I couldn't produce.
I'd probably just unite the methods, and have if-else
before and after the repetitive code. But are there workarounds?
type MAYBE = Result<(), Box<dyn Error>>;
struct MyWriter {
wr: Writer<Box<dyn Write + Send>>
}
impl MyWriter {
...
pub fn write_tags(&mut self, elt: &ElementWriter<Box<dyn Write + Send>>, tags: Tags) -> MAYBE {
// this code repeats
if tags.0.len() > 0 {
elt.write_inner_content(|writer| {
for (k, v) in &tags.0 {
writer.create_element("tag").with_attributes(
vec![("k", &k as &str), ("v", &v as &str)].into_iter()
).write_empty()?;
}
Ok(()) // this is inside closure
})?;
}
else { elt.write_empty()?; }
Ok(())
}
pub fn write_node(&mut self, node: Node) -> MAYBE {
let mut elt = self.wr.create_element(...);
// ^^^^^^^ first mutable borrow
self.write_tags(elt, node.tags)?;
// ^^^^^^^^^^^^ second mutable borrow
Ok(())
}
pub fn write_way(&mut self, way: Way) -> MAYBE {
let mut elt = self.wr.create_element(...);
self.write_tags(elt, way.tags)?;
Ok(())
}
}