Skip to content

Instantly share code, notes, and snippets.

@aucker
Created April 22, 2022 14:56
Show Gist options
  • Save aucker/97b5e94f1253fc0bbb4fc9381f995b66 to your computer and use it in GitHub Desktop.
Save aucker/97b5e94f1253fc0bbb4fc9381f995b66 to your computer and use it in GitHub Desktop.
some type convert

Converting a &str to a String

There are several ways to convert.

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

Converting String to &str

  • &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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment