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

Answer from huon on Stack Overflow
Discussions

U8 array to string
Hello guys let's suppose that I have this struct: struct A { f0: u8, f1; u16, description : [u8;16], } the instance of this struct is filled with data coming from a serial port. What I want to do now is c… More on users.rust-lang.org
🌐 users.rust-lang.org
8
0
March 22, 2024
More efficient conversion from utf8 bytes to a string?
I've made a function to reliably convert utf-8 grapheme clusters stored in a 4-byte variable into a String. I'd like to know if there could be some alterantive way of making this more efficient by avoiding some steps,… More on users.rust-lang.org
🌐 users.rust-lang.org
7
0
April 30, 2022
rust - How do I convert a Vector of bytes (u8) to a string? - Stack Overflow
I am trying to write simple TCP/IP client in Rust and I need to print out the buffer I got from the server. How do I convert a Vec (or a &[u8]) to a String? More on stackoverflow.com
🌐 stackoverflow.com
Converting String to byte array or vector

To get a read-only view into the string, you can use the as_bytes method. To convert it into an owned vector, you can use into_bytes.

To convert back, you can use from_utf8, which checks to make sure that your modifications didn't break the invariant that a str must always contain a valid utf-8 string, or from_utf8_unchecked, which skips that check, if you're sure that it's valid and you can't afford the time cost of the check.

More on reddit.com
🌐 r/rust
8
2
August 8, 2015
🌐
Reddit
reddit.com › r/rust › converting a section of a vec to a string without additional memory allocations
r/rust on Reddit: Converting a section of a Vec<u8> to a string without additional memory allocations
November 6, 2023 -

So say in Rust i have a Vec<u8> , say i read it from some socket. I want to take a piece of that vec, say the 1..5 bytes, and convert that to String. However, i want to do it with only memory allocations for the new String object.

What i see so far is

String::from_utf8(req_buf[1..5].to_vec()).unwrap()

My concern though is it seems like .to_vec() would create a whole vector just to satisfy the from_utf8 requirements.

Is the rust compiler smart enough to not allocate memory for to_vec() ? Or is there a different way to do this?

🌐
Rust
docs.rs › byte_string
byte_string - Rust
The `byte_string` crate provides two types: `ByteStr` and `ByteString`. Both types provide a `Debug` implementation that outputs the slice using the Rust byte string syntax. `ByteStr` wraps a byte slice (`[u8]`). `ByteString` wraps a vector of bytes (`Vec `).
🌐
Rust
doc.rust-lang.org › std › string › struct.String.html
String in std::string - Rust
It is more clear, however, how &s[i..j] should work (that is, indexing with a range). It should accept byte indices (to be constant-time) and return a &str which is UTF-8 encoded. This is also called “string slicing”. Note this will panic if the byte indices provided are not character ...
Find elsewhere
🌐
Medium
medium.com › @trivajay259 › how-to-turn-a-rust-string-into-bytes-and-back-the-clear-modern-guide-d3bd63dcbd31
How to Turn a Rust String into Bytes (and Back) — The Clear, Modern Guide | by Ajay Kumar | Medium
October 31, 2025 - We’ll also cover the reverse (bytes → string), UTF-8 pitfalls, and performance tips you’ll actually use. // 1) Borrow the bytes (zero-copy): &str -> &[u8] let s: &str = "hello"; let bytes_view: &[u8] = s.as_bytes(); // no allocation · // 2) Own the bytes by copying: &str -> Vec<u8> let bytes_vec: Vec<u8> = s.as_bytes().to_vec(); // allocates & copies// 3) Move the bytes out of a String: String -> Vec<u8> let owned: String = String::from("hello"); let moved: Vec<u8> = owned.into_bytes(); // no copy; consumes `owned`
🌐
Peterlyons
peterlyons.com › problog › 2017 › 12 › rust-converting-bytes-chars-and-strings
rust converting bytes chars and strings | Peter Lyons
December 16, 2017 - // You can also start from a byte string b"hello world" and debug print that to get the // utf8 encoded decimal values println!("hello byte string: {:?}", b"hello world"); // OK so let's say you have an array of u8s let array_of_u8 = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]; // [u8] to String (lossy) // Any invalid bytes that are not utf8 will be replaced with // the unicode replacement character '\u{FFFD}' // You get a Cow (Clone on Write) not exactly a String let string_utf8_lossy = String::from_utf8_lossy(&array_of_u8); println!("string_utf8_lossy: {}", string_utf8_lossy); //
🌐
Rust Programming Language
users.rust-lang.org › help
U8 array to string - help - The Rust Programming Language Forum
March 22, 2024 - Hello guys let's suppose that I have this struct: struct A { f0: u8, f1; u16, description : [u8;16], } the instance of this struct is filled with data coming from a serial port. What I want to do now is creating a json object like the following one and print it: let object = serde_json::json!({ "f0": a.f0, "f1": a.f1, "description": std::str::from_utf8(&a.description).unwrap(), }); println!("{}",serde_json::to_string_pretty(&object).un...
🌐
GitHub
gist.github.com › jimmychu0807 › 9a89355e642afad0d2aeda52e6ad2424
Conversion between String, str, Vec<u8>, Vec<char> in Rust · GitHub
My favourite about Rust would be transforming String using let char3: Vec<char> = src3.chars().collect::<Vec<_>>(); into Vec<char>, it makes so much sense! ... Just found that an alternative way of converting String to Vec is this String::into_bytes().
🌐
Rust
docs.rs › bstr
bstr - Rust
Byte strings are just like standard Unicode strings with one very important difference: byte strings are only conventionally UTF-8 while Rust’s standard Unicode strings are guaranteed to be valid UTF-8.
🌐
Rust Wiki
rustwiki.org › en › rust-by-example › std › str.html
Strings - Rust By Example
There are multiple ways to write string literals with special characters in them. All result in a similar &str so it's best to use the form that is the most convenient to write. Similarly there are multiple ways to write byte string literals, which all result in &[u8; N].
🌐
DEV Community
dev.to › moekatib › a-deep-dive-into-strings-in-rust-4hhp
A Deep Dive Into Strings in Rust - DEV Community
June 27, 2023 - At its most basic level, a string ... as a stream of UTF-8 bytes. Strings are created using double quotes "". ... In this code snippet, s is a string that contains the text "Hello, World!". In Rust, a string literal is a slice (&str) that points to a specific section of our ...
🌐
Compiler Explorer
godbolt.org
Compiler Explorer
Compiler Explorer is an interactive online compiler which shows the assembly output of compiled C++, Rust, Go (and many more) code.
🌐
Rust
docs.rs › byte-strings
byte_strings - Rust
Featuring the c_str! macro to create valid C string literals with literally no runtime cost! #[macro_use] extern crate byte_strings; /// Some lib mod safe { use ::std::{ ffi::CStr, os::raw::{c_char, c_int}, }; /// private unsafe C FFI mod ffi { use super::*; extern "C" { pub fn puts (_: *const c_char) -> c_int ; } } /// lib API: safe Rust wrapper => uses `CStr` pub fn puts (message: &'_ CStr) -> i32 { unsafe { ffi::puts(message.as_ptr()) as i32 } } } fn main () { safe::puts(c!("Hello, World!")); }
🌐
MAVLink
mavlink.io › en › messages › common.html
MAVLINK Common Message Set (common.xml) | MAVLink Guide
2 weeks ago - The MAVLink common message set contains standard definitions that are managed by the MAVLink project. The definitions cover functionality that is considered useful to most ground control stations and autopilots.
Top answer
1 of 6
322

To convert a slice of bytes to a string slice (assuming a UTF-8 encoding):

use std::str;

//
// pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
//
// Assuming buf: &[u8]
//

fn main() {

    let buf = &[0x41u8, 0x41u8, 0x42u8];

    let s = match str::from_utf8(buf) {
        Ok(v) => v,
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };

    println!("result: {}", s);
}

The conversion is in-place, and does not require an allocation. You can create a String from the string slice if necessary by calling .to_owned() on the string slice (other options are available).

If you are sure that the byte slice is valid UTF-8, and you don’t want to incur the overhead of the validity check, there is an unsafe version of this function, from_utf8_unchecked, which has the same behavior but skips the check.

If you need a String instead of a &str, you may also consider String::from_utf8 instead.

The library references for the conversion function:

  • std::str::from_utf8
  • std::str::from_utf8_unchecked
  • std::string::String::from_utf8
2 of 6
183

I prefer String::from_utf8_lossy:

fn main() {
    let buf = &[0x41u8, 0x41u8, 0x42u8];
    let s = String::from_utf8_lossy(buf);
    println!("result: {}", s);
}

It turns invalid UTF-8 bytes into � and so no error handling is required. It's good for when you don't need that and I hardly need it. You actually get a String from this. It should make printing out what you're getting from the server a little easier.

Sometimes you may need to use the into_owned() method since it's clone on write.

🌐
Mkyong
mkyong.com › home › java › how to convert byte[] array to string in java
How to convert byte[] array to String in Java | mkyong.com
January 18, 2022 - Reply Helpful Report Spam or advertising Abusive or offensive Off topic ... The issue I find with this byte string conversion is starting from byte{], convert it to String, then retrieve the original byte{} again!
🌐
Base64 Decode and Encode
base64decode.net
Base64 Decode and Encode - Online Tool
Base64 encoding schemes are generally used when there is a need to encode binary information that needs to be stored and transferred over media that are developed to deal with textual information. This guarantees that the data stays unchanged without modification during transfer.