The String::new()
function creates a new, empty string. The String::from()
and to_string()
functions create a new string from an existing string slice. The difference is that String::from()
can take any string slice, while to_string()
only works on types that implement the Display
trait.
Examples:
// Create a new, empty string.
let mut s = String::new();
// Create a new string from a string literal.
let s = String::from("Hello, world!");
// Create a new string from a variable that implements the `Display` trait.
let x = 5;
let s = x.to_string();
In general, it is recommended to use String::from()
when converting a string slice to a string, and to_string()
when converting a value of another type to a string. However, there are some cases where it may be more readable or efficient to use the other function.
For example, if you are converting a string literal to a string, it is often more readable to use to_string()
, because it makes it clear that the value is being converted to a string.
let s = "Hello, world!".to_string();
This is equivalent to the following code, but it is more readable:
let s = String::from("Hello, world!");
Another example is when you are converting a value of another type to a string, and you know that the value implements the Display
trait. In this case, it is often more efficient to use to_string()
, because it does not require allocating a new copy of the string.
let x = 5;
let s = x.to_string();
This is equivalent to the following code, but it is more efficient:
let s = String::from(x.to_string());