将 str 转换为 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]

然而,文件 指出:

Strs 的实际表示具有到片的直接映射: & str 等于 & [ u8]。

62066 次浏览

You can use the as_bytes method:

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)