将字符串传递给函数读取特征

dbr*_*dbr 8 file-io rust

我想在第三方库(xmltree-rs)中调用此函数:

pub fn parse<R: Read>(r: R) -> Element {
Run Code Online (Sandbox Code Playgroud)

预期的用例是给它一个文件,如下:

let e: Element = Element::parse(File::open("tests/data/01.xml").unwrap());
Run Code Online (Sandbox Code Playgroud)

但是我有一个String我想通过的,模糊地这样:

xmltree::Element::parse("<example>blah</example>".to_owned());
Run Code Online (Sandbox Code Playgroud)

但是,这当然会出错:

error: the trait `std::io::Read` is not implemented for the type `collections::string::String` [E0277]
Run Code Online (Sandbox Code Playgroud)

如果没有写临时文件,我该怎么做?(例如在Python中我会使用StringIO模块将字符串包装在类似文件的对象中)

Vee*_*rac 18

要找出实现特征的内容,请转到该特征的页面底部.

在这种情况下,最有前途的实施者是&'a [u8]Cursor<Vec<u8>>.

您可以获取&[u8]&strString致电as_bytes(),以自动反引用,并注意DerefString秒.或者,如果仅使用ASCII子集,则可以使用字节文字.