snippetrustCritical
How do I convert a Vector of bytes (u8) to a string?
Viewed 0 times
byteshowconvertvectorstring
Problem
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
How do I convert a
Vec (or a &[u8]) to a String?Solution
To convert a slice of bytes to a string slice (assuming a UTF-8 encoding):
The conversion is in-place, and does not require an allocation. You can create a
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,
If you need a String instead of a &str, you may also consider
The library references for the conversion function:
use std::str;
//
// pub fn from_utf8(v: &[u8]) -> Result
//
// 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
Context
Stack Overflow Q#19076719, score: 320
Revisions (0)
No revisions yet.