generic struct
假设我们有这样一个结构体
#[derive(Debug)]struct Square {x: u32,y: u32,}
我们要开发一个print函数将这个结构体打印出来
fn print(s: &Square) {println!("{:?}", s);}
这时候有新的需求,假如一个新的类型Point
#[derive(Debug)]struct Point {x: u32,y: u32,z: u32,}
同样也要打印这个结构体,这时候就可以用泛型
fn print<S>(s: &S)where S: Debug{println!("{:?}", s);}
这个print函数能接收所以实现了Debug这个trait的结构体
Iterator
Iterator这个trait有一个associatedType,在where clause中,同样能对这个type做限制
fn debug_iter<I>(iter: I)where I: Iterator,I::Item: Debug {for item in iter {println!("{:?}", item);}}
debug_iter除了限制了入参iter之外,还限制了Item associatedtype必须实现Debug
