I want to call this function in a 3rd party library (xmltree-rs):
pub fn parse<R: Read>(r: R) -> Element {
The expected use case is to give it a file, like so:
let e: Element = Element::parse(File::open("tests/data/01.xml").unwrap());
However I have a String
which I want to pass, vaguely like this:
xmltree::Element::parse("<example>blah</example>".to_owned());
However this, of course, gives an error:
error: the trait `std::io::Read` is not implemented for the type `collections::string::String` [E0277]
How would I do this, short of writing a temporary file? (e.g in Python I would use the StringIO module to wrap the string in a file-like object)
To find out what implements a trait, go to the bottom of the page for that trait.
In this case, the most promising looking implementers are &'a [u8]
and Cursor<Vec<u8>>
.
You can obtain a &[u8]
from a &str
or String
by calling as_bytes()
, taking note of automatic dereferencing and Deref
on String
s. Alternatively, you could use a byte literal if you are only using the ASCII subset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With