Rustジェネリクス

様々な型に対応できる処理に対応できるのがジェネリクス

#[derive(Debug)]
struct Sample<T> {
	name:String,
	value:T
}

fn main() {
	let taro = Sample {
		name:String::from("Taro"),
		value:String::from(("this is message."))
	};
	let hanako = Sample {
		name:String::from("Hanako"),
		value: 1234
	};
	println!("{:?}", taro);
	println!("{:?}", hanako);
}

SampleにVecフィールドを追加する

#[derive(Debug)]
struct Sample<T:core::fmt::Debug> {
	name:String,
	value:Vec<T>
}

impl<T:core::fmt::Debug> Sample<T> {
	fn print_values(&self) {
		println!("*** {} ***", &self.name);
		for item in &self.values {
			println!("{:?}", item);
		}
	}
}

fn sample<T:core::fmt::Debug>(name:&str, values:Vec<T>)
	-> Sample<T>{
		Sample{name:String::from(name), values:values}
	}

fn main() {
	let taro = sample("Taro",
		vec![123, 456, 789]);
	taro.print_values();
	let hanako = sample("Hanako",
		vec!["Hello", "Welcome", "Bye!"]);
	hanako.print_values();
}
trait Print {
	fn print(&self) {
		println!("not implmented...");
	}
}

struct Person {
	name: String,
	mail: String,
	age: i32
}

struct Student {
	name: String,
	mail:String,
	grade: i32
}

impl Print for Person {
	fn print(&self) {
		println!("Person: {}<{}>({})", &self.name, &self.mail, &self.age);
	}
}

impl Print for Student {
	fn print(&self) {
		println!("Student [grade {}]{}<{}>", &self.grade, &self.name, &self.mail);
	}
}

fn person(name:&str, mail:&str, age:i32)->Box<Person>{
	Box::new(Person{name:String::from(name), mail:String::from(mail), age:age})
}

fn student(name:&str, mail:&str, grade:i32)->Box<Student>{
	Box::new(Student{name:String::from(name), mail:String::from(mail), grade})
}