Rust基础之泛型



例子1
fn largest_i32(list:&[i32])->&i32 {
    let mut largest=&list[0];

    for item in list{
        if item > largest{
            largest=item;
        }
    }

    largest
}

fn largest_char(list:&[char])->&char{
    let mut largest = &list[0];

    for item in list {
        if item>largest{
            largest=item;
        }
    }

    largest
}

fn main() {
    let number_list=vec![34,50,25,100,65];
    let result=largest_i32(&number_list);
    println!("The largest number is {}",result);

    let char_list=vec!['y','m','a','q'];
    let result=largest_char(&char_list);
    println!("The largest char is {}",result);
}

例子2
fn largest<T:std::cmp::PartialOrd>(list:&[T])->&T {
    let mut largest=&list[0];

    for item in list{
        if item > largest{
            largest=item;
        }
    }

    largest
}

fn main() {
    let number_list=vec![34,50,25,100,65];
    let result=largest(&number_list);
    println!("The largest number is {}",result);

    let char_list=vec!['y','m','a','q'];
    let result=largest(&char_list);
    println!("The largest char is {}",result);
}

例子3
struct Point<T>{
    x:T,
    y:T,
}

fn main() {
    let integer=Point{x:5,y:10};
    let float=Point{x:1.0,y:4.0};
}

例子4
struct Point<T,U>{
    x:T,
    y:U,
}

fn main() {
    let integer=Point{x:5,y:10.0};
    let float=Point{x:1,y:4.0};
}

例子5,枚举中的泛型
enum Option<T> {
    Some(T),
    None,
}

enum Result<T,E> {
    Ok(T),
    Err(E),
}


例子6,方法定义中的泛型
struct Point<T>{
    x:T,
    y:T,
}

impl <T> Point<T> {
    fn x(&self)->&T{
        &self.x
    }
}

fn main() {
    let p = Point{x:5,y:10};
    println!("p.x={}",p.x());
}

例子7
struct Point<X1,Y1>{
    x:X1,
    y:Y1
}

impl<X1,Y1> Point<X1,Y1> {
    fn mixup<X2,Y2>(self,other:Point<X2,Y2>)->Point<X1,Y2>{
        Point{
            x:self.x,
            y:other.y,
        }
    }
}

fn main(){
    let p1=Point{x:5,y:10.4};
    let p2=Point{x:"Hello",y:'c'};
    let p3=p1.mixup(p2);
    println!("p3.x={},p3.y={}",p3.x,p3.y);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为风而战

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值