Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass string to function taking Read trait

Tags:

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)

like image 518
dbr Avatar asked Sep 20 '15 01:09

dbr


1 Answers

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 Strings. Alternatively, you could use a byte literal if you are only using the ASCII subset.

like image 64
Veedrac Avatar answered Oct 27 '22 01:10

Veedrac