Skip to content

Instantly share code, notes, and snippets.

@s3rvac
Created April 16, 2017 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s3rvac/acdfeff738d8a460e55dadd2ef38c58a to your computer and use it in GitHub Desktop.
Save s3rvac/acdfeff738d8a460e55dadd2ef38c58a to your computer and use it in GitHub Desktop.
A Rust function that accepts both String or &str and creates a copy of it
// Item::new() accepts both &str and String. When called, it creates a copy of
// the parameter and uses it to initialize the returned item.
//
// The trick is in the use of the Into trait:
// https://doc.rust-lang.org/std/convert/trait.Into.html
struct Item {
id: String
}
impl Item {
fn new<T: Into<String>>(id: T) -> Self {
Item { id: id.into() }
}
}
fn main() {
let item1 = Item::new("123"); // &str
let item2 = Item::new("456".to_string()); // String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment