String::from() in rust
2023-04-18
String::from() basically turns a static string variable to a mutabe variable.
This is what phined have to say:
String::from
in Rust is a function that creates a String
from a string literal or a &str
. A string literal, which is of type &'static str
, is an immutable string slice that is embedded into the executable. On the other hand, String
is a mutable and growable string buffer allocated on the heap. The String::from
function creates a heap-allocated String
and copies the data from the static string into it Source 4.
Here's an example:
#![allow(unused)] fn main() { let static_str = "Hello, world!"; let string = String::from(static_str); }
In this example, static_str
is of type &'static str
, and string
is of type String
. The String::from
function is used to create a mutable String
from the immutable &'static str
.
You can also use .to_string()
or .to_owned()
on a string literal to achieve the same result:
#![allow(unused)] fn main() { let string = static_str.to_string(); let string = static_str.to_owned(); }
Both .to_string()
and .to_owned()
work similarly to String::from
. In Rust versions before 1.9.0, String::from
was faster than .to_string()
, but from version 1.9.0 onwards, they have the same performance Source 3.