Why does Rust have String
and str
? What are the differences between String
and str
? When does one use String
std::String
is simply a vector of u8
. You can find its definition in source code . It's heap-allocated and growable.
#[derive(PartialOrd, Eq, Ord)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct String {
vec: Vec,
}
str
is a primitive type, also called string slice. A string slice has fixed size. A literal string like let test = "hello world"
has &'static str
type. test
is a reference to this statically allocated string.
&str
cannot be modified, for example,
let mut word = "hello world";
word[0] = 's';
word.push('\n');
str
does have mutable slice &mut str
, for example:
pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)
let mut s = "Per Martin-Löf".to_string();
{
let (first, last) = s.split_at_mut(3);
first.make_ascii_uppercase();
assert_eq!("PER", first);
assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);
But a small change to UTF-8 can change its byte length, and a slice cannot reallocate its referent.