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

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

2 Likes

My favourite post about strings in rust:

(Cleverly disguised as being about fizzbuzz :smirk: )

1 Like

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: Strings - The Rust Programming Language

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

https://stackoverflow.com/questions/24158114/what-are-the-differences-between-rusts-string-and-str

1 Like

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.

1 Like