string - 如何将 &str 转换为 &[u8]

标签 string rust slice

这看起来微不足道,但我找不到实现它的方法。

例如,

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)

关于string - 如何将 &str 转换为 &[u8],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31289588/

相关文章:

string - NSString 不能隐式转换为 String - 但一切都是 NSString

android - 我不能动态地执行 getResources.getString 吗?

C++ Clean String to int 转换

arrays - golang 将字符串添加到 slice ...interface{}

cassandra - Hector Cassandra 数据检索

java - 从包含 <img src> 标签的 Java 字符串中提取 url

rust - `type Item` 特征中的 `Iterator` 是什么意思

rust - 根据条件如何将输出分配给变量匹配类型

rust - 为什么可变的 self 借用不会变成不可变的?

Python 检索列表中标记之间的嵌套值列表