Rust Programming: Create a New String

0

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:

Rust
// 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.

Rust
let s = "Hello, world!".to_string();

This is equivalent to the following code, but it is more readable:

Rust
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.

Rust
let x = 5;
let s = x.to_string();

This is equivalent to the following code, but it is more efficient:

Rust
let s = String::from(x.to_string());


Post a Comment

0Comments
Post a Comment (0)