Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a bytes::bytes::Bytes from a std::string::String?

Tags:

rust

I'm trying to invoke an AWS Lambda function using the Rusoto library. The request has a JSON-encoded payload which I currently have as a String, but the library insists on a bytes::bytes::Bytes struct for this. I haven't been able to find a way to convert the String to the Bytes (not the most googleable thing in the world) - can anyone help me out? Thanks.

expected struct `bytes::bytes::Bytes`, found struct `std::string::String`
like image 613
user1381745 Avatar asked Jul 19 '26 17:07

user1381745


1 Answers

Bytes implements From/Into for String to allow conversion from strings to the bytes representing that string in 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"
}

Try it in the playground

like image 169
Smitop Avatar answered Jul 23 '26 13:07

Smitop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!