let hello1 = "Hello, world!"; let hello2 = "Hello, world!".to_string(); let hello3 = String::from("Hello, world!");
String is the dynamic heap string type, like Vec : use it when you need to own or modify your string data. str is an immutable1 sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer.
Rust doesn't sugar coat a lot of the ugliness and complexity of string handling from developers like other languages do and therefore helps in avoiding critical mistakes in the future. By construction, both string types are valid UTF-8. This ensures there are no misbehaving strings in a program.
The str type, also called a 'string slice', is the most primitive string type. It is usually seen in its borrowed form, &str . It is also the type of string literals, &'static str . String slices are always valid UTF-8.
A String is stored as a vector of bytes ( Vec<u8> ), but guaranteed to always be a valid UTF-8 sequence. String is heap allocated, growable and not null terminated. &str is a slice ( &[u8] ) that always points to a valid UTF-8 sequence, and can be used to view into a String , just like &[T] is a view into Vec<T> .
let hello1 = "Hello, world!";
This creates a string slice (&str
). Specifically, a &'static str
, a string slice that lives for the entire duration of the program. No heap memory is allocated; the data for the string lives within the binary of the program itself.
let hello2 = "Hello, world!".to_string();
This uses the formatting machinery to format any type that implements Display
, creating an owned, allocated string (String
). In versions of Rust before 1.9.0 (specifically because of this commit), this is slower than directly converting using String::from
. In version 1.9.0 and after, calling .to_string()
on a string literal is the same speed as String::from
.
let hello3 = String::from("Hello, world!");
This converts a string slice to an owned, allocated string (String
) in an efficient manner.
let hello4 = "hello, world!".to_owned();
The same as String::from
.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With