将 str 转换为 &[u8]
Converting a str to a &[u8]
这看起来微不足道,但我找不到实现它的方法。
例如,
fn f(s: &[u8]) {}
pub fn main() {
let x = "a";
f(x)
}
编译失败:
error: mismatched types:
expected `&[u8]`,
found `&str`
(expected slice,
found str) [E0308]
documentation,然而,指出:
The actual representation of strs have direct mappings to slices: &str
is the same as &[u8].
您可以使用as_bytes方法:
fn f(s: &[u8]) {}
pub fn main() {
let x = "a";
f(x.as_bytes())
}
或者,在您的特定示例中,您可以使用字节文字:
let x = b"a";
f(x)
这看起来微不足道,但我找不到实现它的方法。
例如,
fn f(s: &[u8]) {}
pub fn main() {
let x = "a";
f(x)
}
编译失败:
error: mismatched types:
expected `&[u8]`,
found `&str`
(expected slice,
found str) [E0308]
documentation,然而,指出:
The actual representation of strs have direct mappings to slices: &str is the same as &[u8].
您可以使用as_bytes方法:
fn f(s: &[u8]) {}
pub fn main() {
let x = "a";
f(x.as_bytes())
}
或者,在您的特定示例中,您可以使用字节文字:
let x = b"a";
f(x)