在rust中可以为泛型进行多个trait进行组合,然后这个泛型必须实现指定的多个trait,一般通过 +来组合多个trait,当你使用 Trait 组合时,Rust 会自动为这些 Trait 创建一个公共的超 Trait,这个超 Trait 被称为自动 Trait(auto trait)。例如我们求圆,长方形,正方形,梯形等的面积和周长,我们可以定义一个周长的trait和一个求面积的trait,然后长方形,圆都实现这两个tarit。
定义trait
/// 1.周长trait
trait Perimeter{
type Item;
fn perimeter(&self)->Self::Item;
}
/// 2.面积trait
trait Extent{
type Item;
fn extent(&self)->Self::Item;
}
上面我们定义了两个trait分别是求长方形,正方形,圆的面积和周长。
实现trait
/// 定义长方形结构体
struct Rectangle{
width:i32,
height:i32,
}
/// 定义圆结构体
struct Round{
radius:f32,
}
/// 定义正方形结构体
struct Square{
width:i32,
}
impl Perimeter for Rectangle{
type Item = i32;
fn perimeter(&self) -> Self::Item {
2 *(self.width + self.height)
}
}
impl Perimeter for Round{
type Item = f32;
fn perimeter(&self) -> Self::Item {
2 *3.14 * self.radius
}
}
impl Perimeter for Square{
type Item = i32;
fn perimeter(&self) -> Self::Item {
4 * self.width
}
}
impl Extent for Rectangle{
type Item = i32;
fn extent(&self)->Self::Item{
self.width * self.height
}
}
impl Extent for Round{
type Item = f32;
fn extent(&self)->Self::Item{
3.14*self.radius*self.radius
}
}
impl Extent for Square{
type Item = i32;
fn extent(&self)->Self::Item{
self.width * self.width
}
}
使用 Trait 组合
fn compute_extent_perimeter<T:Extent + Perimeter>(item:T){
item.extent();
item.perimeter();
}
/// 调用compute_extent_perimeter函数
main(){
let rtl = Rectangle{
width:4,
height:6,
};
compute_extent_perimeter(rtl);
let rd= Round{
radius:4.5,
};
compute_extent_perimeter(rd);
let s = Square{
width:6
};
compute_extent_perimeter(s);
}
上述我们创建一个compute_extent_perimeter函数,函数的参数必须同时实现Extent 和 Perimeter两个trait,然后在compute_extent_perimeter函数中调用了实现两个trait的函数,分别计算出面积和周长。这样使得我们的代码可以很灵活的进行trait得组合,通过这种方式,你可以确保泛型类型参数具有所需的行为,同时保持代码的灵活性和可重用性。
本文使用 markdown.com.cn 排版