Skip to content

Instantly share code, notes, and snippets.

@KodrAus
Last active August 21, 2016 10:29
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 KodrAus/dc0015500a775eab9a7c2ba58cf3953b to your computer and use it in GitHub Desktop.
Save KodrAus/dc0015500a775eab9a7c2ba58cf3953b to your computer and use it in GitHub Desktop.
Rust Generics
#[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