to_string()
fn main() {
let new_string = "hello".to_string();
}
to_string() turns a &str to String.
to_owned()
fn main() {
let new_string = "hello".to_owned();
}
&str is an immutable reference to a String, use to_owned() turns it into a String you own and can do things with.
String::from()
fn main() {
let new_string = String::from("hello");
}
String::push_str()
fn main() {
let mut new_string = String::new();
new_string.push_str("hello");
new_string.push_str(" world");
println!("{}", new_string);
}
format!()
fn main() {
let world_var = "world";
let new_string = format!("hello {}", world_var);
}
use the macro to format some more complex formatting with &str as input.
into()
fn main() {
let new_string = "hello".into();
}
This is a simple conversion if you don't care about the ambiguity.
- &String types turn into &str if the method call needs it
let my_str: &str = &my_string
, if you want to explicitly specify a &str type