Rust 中,trait,关联类型,泛型,这几个概念本身并不复杂。但是这些东西合在一起使用的时候,经常让初学者感觉天花乱坠,摸不着头脑。本文就用一些简单的例子,来梳理一下这些概念,以及它们之间的配合使用方式。
关联类型
关联类型是 trait 定义中的类型占位符。定义的时候,并不定义它的具体的类型是什么。在 impl 这个 trait 的时候,才为这个关联类型赋予确定的类型。也就是说,在实现的时候,才知道它的具体类型是什么。
举个例子,我们自定义一个 trait 叫:Converter
。
pub trait Converter {
type Output;
fn convert(&self) -> Self::Output;
}
例子:
pub trait Converter {
type Output;
fn convert(&self) -> Self::Output;
}
struct MyInt;
impl Converter for MyInt {
type Output = i32;
fn convert(&self) -> Self::Output {
42
}
}
fn main() {
let my_int = MyInt;
let output = my_int.convert();
println!("