What is the difference of: "strings"?


#1

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);
}


#2

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.


#3

My favourite post about strings in rust:

(Cleverly disguised as being about fizzbuzz :smirk: )


#4

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


#5

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


#6

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


#7

&'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.