将字符串传递给具有读取特征的函数 [英] Pass string to function taking Read trait
问题描述
我想在第3方库( xmltree-rs )中调用此函数:
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());
但是我有一个想要传递的String
,隐约是这样的:
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]
如果不写临时文件,我该怎么办? (例如,在Python中,我可以使用 StringIO模块来包装一个类似文件的对象中的字符串)
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.
在这种情况下,最有前途的实现者是&'a [u8]
和Cursor<Vec<u8>>
.
In this case, the most promising looking implementers are &'a [u8]
and Cursor<Vec<u8>>
.
您可以通过调用String
获取&[u8]
. rel ="noreferrer"> as_bytes()
,注意自动取消引用和
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.
这篇关于将字符串传递给具有读取特征的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!