如何从 std::string::String 获取 bytes::bytes::Bytes?

use*_*745 2 rust

我正在尝试使用 Rusoto 库调用 AWS Lambda 函数。该请求有一个 JSON 编码的有效负载,我目前将其作为字符串,但库坚持bytes::bytes::Bytes为此使用结构。我一直无法找到将字符串转换为字节的方法(不是世界上最适合谷歌的东西) - 谁能帮我?谢谢。

expected struct `bytes::bytes::Bytes`, found struct `std::string::String`
Run Code Online (Sandbox Code Playgroud)

小智 6

Bytes实现From/ IntoforString以允许从字符串转换为以UTF-8表示该字符串的字节:

use bytes::Bytes;
fn main() {
    let string = "démonstration".to_string();
    println!("{:?}", string); // "démonstration"
    let bytes: Bytes = string.into();
    println!("{:?}", bytes); // b"d\xc3\xa9monstration"
}
Run Code Online (Sandbox Code Playgroud)

在操场上试试