String and str
Difference between String and str
String is similar to Vec<T>. It is similar to the C++ String class.
str is similar to char[]. Just as C++ uses a variable name as a pointer when working with a char array, Rust usually uses str through a reference by putting & in front of it.
Type conversion
How do you convert a String into &str?
Put &* in front of the String. See Deref.
let s = String::from("hello world")
let ss = *s; //str type, Deref coerce
let sss = &*s; //&str
Or use the as_str() function.
let s = String::from("hello world")
let ss = s.as_str; //&str
How do you convert &'static str into String?
Use to_string().
Converting &str into String requires allocation, so avoid it when possible.
let s = "hello world";
let ss = s.to_string();Byte String Literal
b"whatever" is a byte string literal. Its type is buf: &[u8; 8].
let s = b"hello world"; //buf:&[u8;11]
let ss = b"whatever"; //buf:&[u8;8]