Rust Generics
This file contains 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
#[derive(Debug)] | |
struct Person<T> { | |
id: T, | |
title: String | |
} | |
impl <T> Person<T> { | |
fn new<I: Into<String>>(id: T, title: I) -> Self { | |
Person { | |
id: id, | |
title: title.into() | |
} | |
} | |
} | |
//Traits can be implemented for specific bounds, or blanket | |
//Without specialisation, if your bounds collide then you're gonna have a bad time | |
impl ToString for Person<i32> { | |
fn to_string(&self) -> String { | |
format!("i32: {}, {}", self.id, self.title) | |
} | |
} | |
impl ToString for Person<bool> { | |
fn to_string(&self) -> String { | |
format!("bool: {}, {}", self.id, self.title) | |
} | |
} | |
fn main() { | |
let person1 = Person::new(1, "Joe"); | |
let person2 = Person::new(true, String::from("Jan")); | |
println!("1: {} 2: {}", person1.to_string(), person2.to_string()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment