zoukankan      html  css  js  c++  java
  • Rust 泛型

    泛型可以使用在结构体中

    struct Pair<T> {
        x: T,
        y: T,
    }

    其中x,y都属于T类型。

    实现结构体的方法或者关联函数需要在impl关键字后面指定泛型

    impl<T> Pair<T> {
        fn new(x: T, y: T) -> Self {
            Self {
                x,
                y,
            }
        }
    }
    impl<T> Point<T> {
        fn x(&self) -> &T {
            &self.x
        }
    }

    讲到泛型就绕不开trait,trait类似于其他语言中的接口

    具体使用方法如下

    pub trait Summarizable {
        fn summary(&self) -> String;
    }
    pub struct NewsArticle {
        pub headline: String,
        pub location: String,
        pub author: String,
        pub content: String,
    }
    
    impl Summarizable for NewsArticle {
        fn summary(&self) -> String {
            format!("{}, by {} ({})", self.headline, self.author, self.location)
        }
    }

    要希望泛型拥有特定的功能,就必须指定泛型的trait,简称trait bound

    impl<T: Display + PartialOrd> Pair<T> {
        fn cmp_display(&self) {
            if self.x >= self.y {
                println!("The largest member is x = {}", self.x);
            } else {
                println!("The largest member is y = {}", self.y);
            }
        }
    }

    泛型T要有比较和打印功能,就要指定T的trait bound

    有一个易于观看的trait bound语法

    fn some_function<T, U>(t: T, u: U) -> i32
        where T: Display + Clone,
              U: Clone + Debug
    {
    }

    也可以这样写

    fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
    }
  • 相关阅读:
    openstack--9--深入理解虚拟机
    KVM部署、使用、调优
    Mysql主从---删除master.info和relya-log.info实验
    saltstack实战4--综合练习3
    saltstack实战4--综合练习4
    saltstack实战4--综合练习2
    nmap命令-----高级用法
    saltstack实战4--综合练习1
    saltstack实战3--配置管理之pillar
    nmap命令-----基础用法
  • 原文地址:https://www.cnblogs.com/kwebi/p/9462132.html
Copyright © 2011-2022 走看看