将 str 转换为 &[u8] [英] Converting a str to a &[u8]

查看:66
本文介绍了将 str 转换为 &[u8]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来微不足道,但我找不到办法.

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

例如

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] 相同.

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())
}

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

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

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

这篇关于将 str 转换为 &[u8]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆