Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

type conversion - How do I convert a string into a vector of bytes in rust?

That might be the dumbest Rustlang question ever but I promise I tried my best to find the answer in the documentation or any other place on the web.

I can convert a string to a vector of bytes like this:

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

Unfortunately I can't do it this way

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

Because bytes! expects a string literal.

But then, how do I get my foo converted into a vector of bytes?

question from:https://stackoverflow.com/questions/23850486/how-do-i-convert-a-string-into-a-vector-of-bytes-in-rust

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

(&str).as_bytes gives you a view of a string as a &[u8] byte slice (that can be called on String since that derefs to str, and there's also String.into_bytes will consume a String to give you a Vec<u8>.

Use the .as_bytes version if you don't need ownership of the bytes.

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

BTW, The naming conventions for conversion functions are helpful in situations like these, because they allow you to know approximately what name you might be looking for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...