How to Convert a Str to a &[u8] in Rust

Created
Modified

Using as_bytes Function

The as_bytes() method converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the from_utf8 function.

See the following example:

fn main() {
  let s = "abc";
  let b = s.as_bytes();
  println!("{:?}", b);
}
[97, 98, 99]

Using a Byte Literal

You can use a byte literal. For example,

fn main() {
  let b = b"abc";
  println!("{:?}", b);
}
[97, 98, 99]

Rust Errors

non-ASCII character in byte constant:

let b = b"a̐bc";
error: non-ASCII character in byte constant
 --> src/main.rs:2:14
  |
2 |   let b = b"a̐bc";
  |              ^ byte constant must be ASCII but is '\u{310}'
  |
help: if you meant to use the UTF-8 encoding of '\u{310}', use \xHH escapes
  |
2 |   let b = b"a\xCC\x90bc";

Related Tags