rust 泛型01

同一时间泛型只能是同一种类型,否则就用多个泛型参数。结构体这里的泛型参数T和K,就表示不同的参数类型,当然T和K也可以是同一种类型。

#[derive(Debug)]
struct Base<T,K> {
    x: T,
    y: T,
    z: K,
}
impl<T,K> Base<T,K> {
    fn new(a:T, b:T, c: K) -> Base<T,K> {
        Base { x: a, y: b, z: c}
    }
}


fn main() {
    let a = Base::new(1, 2,"str");
    let b = Base::new(1.2, 2.2,"String".to_string());
    let c = Base::new(10,100,3.1);
    let d = Base::new(1,2,3); // 不同泛型参数,同一种类型

    println!("a: => {:?}\nb: => {:?}\nc: => {:?}\nd: => {:?}",a,b,c,d);
}

output:

a: => Base { x: 1, y: 2, z: "str" }
b: => Base { x: 1.2, y: 2.2, z: "String" }
c: => Base { x: 10, y: 100, z: 3.1 }
d: => Base { x: 1, y: 2, z: 3 }

posted @ 2022-07-05 22:09  天使不设防  阅读(14)  评论(0编辑  收藏  举报