string 将 str 转换为 &[u8]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31289588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:25:19  来源:igfitidea点击:

Converting a str to a &[u8]

stringrustslice

提问by ynimous

This seems trivial, but I cannot find a way to do it.

这似乎微不足道,但我找不到办法做到这一点。

For example,

例如,

fn f(s: &[u8]) {}

pub fn main() {
    let x = "a";
    f(x)
}

Fails to compile with:

无法编译:

error: mismatched types:
 expected `&[u8]`,
    found `&str`
(expected slice,
    found str) [E0308]

documentation, however, states that:

然而,文档指出:

The actual representation of strs have direct mappings to slices: &str is the same as &[u8].

strs 的实际表示直接映射到切片:&str 与 &[u8] 相同。

回答by fjh

You can use the as_bytesmethod:

您可以使用as_bytes方法:

fn f(s: &[u8]) {}

pub fn main() {
    let x = "a";
    f(x.as_bytes())
}

or, in your specific example, you could use a byte literal:

或者,在您的具体示例中,您可以使用字节文字:

let x = b"a";
f(x)