What is the difference?

I was reading the book and I got kinda confused about the main difference between using

let s1 = String::from("Hello");


let s1 = "Hello";

I get the concept under move and copy but I don't get the difference between assigning a string with ::from and without it.

The first case will create a String the second one will be a & 'static str.

1 Like

To be more specific, str is a type that represents a string of characters in memory, regardless of how they got there. String literals (expressions like "my_str") are stored alongside the program and are essentially a part of the program itself, so their lifetime is the 'static lifetime -- the lifetime of the whole program. Therefore their type is &'static str.
The type String, on the other hand, is a string type that owns the str it represents, so it can also change its contents, or pass them on to someone else. The downside is that it requires dynamic allocation of memory, i.e. memory from the heap.


Thank you ::heart:

1 Like