String in Rust
Rust has two types of strings
&str
: It's a simple string, it's just a pointer with just enough information about the data it points to, enough to tell the length, it's also referred to as ref string or string slice
String
: It's is a more complicated string, it is a pointer to it's own data on the heap, so it slower compared to &str and you can do more with it.
A String
is an owned type and because we use &
in front of str
we don't own it.
A string can be made in several ways:
String::from("This string text")
"This is a string text".to_string()
using the format! macro
These below are more of conversion tools.
From()
into()
into()
is a bit tricky compared to From()
, with From()
you already know what type you are converting from but with into()
the compiler is unaware what exactly you want to do so we will tell it what type we want it to convert into.
ERROR:
fn main(){
let my_string = "This is a string".into()
}
FIX:
let my_string: String = "This is a string".into()
Now, the compiler is aware what we want to convert the data into.