-
Notifications
You must be signed in to change notification settings - Fork 1
12月21日学习笔记
特征 trait
1、trait用于定义与其它类型共享的功能,类似于其它语言中的接口;(1)可以通过trait以抽象的方式定义共享的行为;(2)可以使用trait bounds指定泛型是任何拥有特定行为的类型;
2、定义trait
3、实现trait
4、默认实现:可以在定义trait的时候提供默认的行为,trait的类型可以使用默认的行为
5、trait作为参数
定义trait
pub trait GetInformation{
fn get_name(&self) -> &string;
fn get_age(&self) -> u32;
}
实现trait
pub struct Student {
pub name: String,
pub age: u32,
}
impl SchoolName for Student {}
impl GetInformation for Strudent {
fn get_name(&self) -> &String {
&self.name
}
fn get_age(&self) -> u32{
self.age
}
}
pub struct Teacher {
pub name: String,
pub age: u32,
pub subject: String,
}
impl SchoolName for Teacher {
fn get_school_name(&self) -> String {
String::from("GuangmingSchool")
}
}
impl GetInformation for Teacher {
fn get_name(&self) -> &String {
&self.name
}
fn get_age(&self) -> u32{
self.age
}
fn print_information(item: impl GetInformation) {
println!("name = {}", item.get_name());
println!("age = {}", item.get_age());
}
fn main(){
let s = Student{name:"xiaoming".to_string(), age:10};
let t = Teacher{name:"xiaohuang".to_string(), age:30, subject:String::from("math")};
println!("student, name = {}, age = {}", s.get_name(), s.get_age());
println!("teacher, name = {}, age = {}", t.get_name(), t.get_age());
s.get_school_name();
t.get_school_name();
print_information(s);
print_information(t);
}
trait的默认实现
trait SchoolName {
fn get_school_name(&self) -> String {
&(String::from("HongXingSchool")) }
}
默认实现,首先在定义trait里面实现一个默认实现,调用的时候,如果需要用默认实现,函数直接是空就好了,如果不用,可以自己再实现一个,将之前的替换掉。
1、trait_bound语法
2、指定多个trait bound
3、返回trait的类型
fn print_information<T: GetInformation>(item: T) {
println!("name = {}", item.get_name());
println!("age = {}", item.get_age());
}