29

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)

1 Answer 1

41

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much for providing an answer that points back to the Rust docs and thus provides a model for how to answer the question unaided in future.
In some situations (such as dependency injection), you cannot use references (i.e. &). In that case, use Cursor. You can create a new cursor by Cursor::new(s.into_bytes()). In Rust 1.63.0 or later, you can also use VecDeque<u8> created by VecDeque::from(s.into_bytes()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.