Created
April 16, 2017 15:59
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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