What is the difference of: "strings"?


Please, What is the difference between a, b, c, d, e?
fn main()
let a = “a”;
let b = “b”.to_string();
let c: &str = “c”;
let d: &'static str = “d”;
let e = String::new();
println!("{} {} {} {} {} ", a, b, c, d, e);


The best thing to do to understand this is to determine the individual types:
a : &str
b: String
c: &str
d: &str
e: String

Note that a, c and d have a 'static lifetime.

str is a primitive type. You only use it in its reference form &str. This type is immutable. (Not 100% correct, but enough for this explanation). Whenever you write let a = "some string", this will be a &str.

String is a type like anything else you could create yourself. It is heap allocated, like a Vec.

Further reading:
str reference
String reference

Please use formatting. It is easily available through the edit fields menu.


My favourite post about strings in rust:

(Cleverly disguised as being about fizzbuzz :smirk: )


In short str is temporary and/or read-only (borrowed), and String is permanent and read-write (owned).

The book explains it in more detail: https://doc.rust-lang.org/book/second-edition/ch08-02-strings.html


Stackoverflow has (like almost always) the answer :smiley:


Aren’t &'static str (a &str with a static lifetime) permanent? I thought that was included in the data section of the binary


&'static str is a special case. It’s still a borrowed reference to an owned string living elsewhere (owned by the program). It’s just that the “temporary” borrow happens to be as long as your program’s lifetime.