118

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?

3 Answers 3

142

(&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.

6
  • Thank you for your answer. Can you apply that to my example so that I have the equivalent of bytes!(foo) in bar? I tried let bar = (&foo).as_bytes but that doesn't seem to do the trick.
    – Christoph
    Commented May 24, 2014 at 23:17
  • Being more specific it gives me this compile error: attempted to take value of method as_bytes on type &'static str
    – Christoph
    Commented May 24, 2014 at 23:34
  • 1
    Oh, nooooo. I honestly feel like the dumbest man on StackOverflow now. THANKS!
    – Christoph
    Commented May 24, 2014 at 23:46
  • 1
    @huon-dbaupp Compiling your example with Rust 1.2 gives the trait `core::fmt::Display` is not implemented for the type `[u8]` [E0277]. Does that mean your answer needs to be updated to change {} with {:?}? Commented Sep 2, 2015 at 15:41
  • 6
    To be clear, the resulting bytes are in UTF-8 encoding, because that's how Rust stores str and String. (Conceptually, it doesn't make any sense to talk about the "bytes of a string" without talking about encoding.)
    – jbg
    Commented Apr 27, 2019 at 15:05
30

To expand the answers above. Here are a few different conversions between types.

&str to &[u8]:

let my_string: &str = "some string";
let my_bytes: &[u8] = my_string.as_bytes();

&str to Vec<u8>:

let my_string: &str = "some string";
let my_bytes: Vec<u8> = my_string.as_bytes().to_vec();

String to &[u8]:

let my_string: String = "some string".to_owned();
let my_bytes: &[u8] = my_string.as_bytes();

String to Vec<u8>:

let my_string: String = "some string".to_owned();
let my_bytes: Vec<u8> = my_string.into_bytes();

Specifying the variable type is optional in all cases. Just added to avoid confusion.

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5ad228e45a38b4f097bbbba49100ecfc

1
  • thank you. the OP asked for "vector", not "[u8]", and you provided a lot more of the combinations needed.
    – Paul S
    Commented Aug 29 at 19:17
-2
 `let v1: Vec<u8> = string.encode_to_vec();`
 `let v2: &[u8]   = string.as_bytes();`

two work difference, in some of library use ownership of bytes !! if you use as_bytes() see compiler error: must be static.

for example: tokio_uring::fs::File::write_at() get a ownership of bytes !!

but if you need borrowing , use as_bytes()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.