let hello1 = "Hello, world!";
This creates a string slice ( &str ). In particular, &'static str , a string slice that lives on throughout the program. No heap of memory is allocated; the data for the string lives in the binary file of the program itself.
let hello2 = "Hello, world!".to_string();
A formatting mechanism is used to format any type that implements Display , creating its own highlighted string ( String ). In versions of Rust prior to 1.9.0 (especially due to this commit ), this is slower than direct conversion using String::from . In version 1.9.0 and after calling .to_string() in a string literal, the speed is the same as String::from .
let hello3 = String::from("Hello, world!");
This effectively converts a slice of a string into an owned, selected string ( String ).
let hello4 = "hello, world!".to_owned();
Same as String::from .
See also:
- How to create a string directly?
- What are the differences between the string `String` and` str`? Rust?
Shepmaster
source share