【问题标题】:How do I convert a string into a vector of bytes in rust?如何将字符串转换为 rust 中的字节向量?
【发布时间】:2014-07-14 01:38:06
【问题描述】:

这可能是 Rustlang 有史以来最愚蠢的问题,但我保证我会尽力在文档或网络上的任何其他地方找到答案。

我可以像这样将字符串转换为字节向量:

let bar = bytes!("some string");

不幸的是我不能这样做

let foo = "some string";
let bar = bytes!(foo);

因为bytes! 需要一个字符串字面量。

但是,如何将我的 foo 转换为字节向量?

【问题讨论】:

    标签: type-conversion rust


    【解决方案1】:

    (&str).as_bytes 为您提供一个字符串视图作为&[u8] 字节切片(可以在String 上调用,因为它引用str,还有String.into_bytes 将消耗String 到给你一个Vec<u8>

    如果您不需要字节的所有权,请使用 .as_bytes 版本。

    fn main() {
        let string = "foo";
        println!("{:?}", string.as_bytes()); // prints [102, 111, 111]
    }
    

    顺便说一句,naming conventions for conversion functions 在此类情况下很有帮助,因为它们可以让您大致了解您可能要查找的名称。

    【讨论】:

    • 感谢您的回答。你能把它应用到我的例子中,以便我在bar 中拥有相当于bytes!(foo) 的内容吗?我试过let bar = (&foo).as_bytes,但这似乎没有奏效。
    • 更具体地说,它给了我这个编译错误:attempted to take value of method as_bytes on type &'static str
    • 哦,不。老实说,我现在觉得自己是 StackOverflow 上最愚蠢的人。谢谢!
    • @huon-dbaupp 用 Rust 1.2 编译你的例子会得到the trait `core::fmt::Display` is not implemented for the type `[u8]` [E0277]。这是否意味着您的答案需要更新以将{} 更改为{:?}
    • 需要明确的是,生成的字节采用 UTF-8 编码,因为这就是 Rust 存储 strString 的方式。 (从概念上讲,不谈论编码就谈论“字符串的字节”是没有任何意义的。)
    【解决方案2】:
     `let v1: Vec<u8> = string.encode_to_vec();`
     `let v2: &[u8]   = string.as_bytes();`
    

    两个工作区别,在一些库中使用字节的所有权!如果您使用 as_bytes() 请参阅编译器错误:必须是静态的。

    例如:tokio_uring::fs::File::write_at() 获得字节的所有权!

    但如果需要借用,请使用 as_bytes()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 2013-10-05
      • 2021-09-19
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多