Rust中的范型-学习随笔

函数中的范型(含范型特征约束)

fn get_largest<T: std::cmp::PartialOrd>(a: T, b: T) -> T {
    if a > b {
        a
    }
    else {
        b
    }
}


fn main() {
    println!("{}", get_largest::<u32>(10, 20));
    println!("{}", get_largest::<f32>(0.1, 0.4));
}

 

结构体中的范型

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

// T满足两种特征Clone 和 std::cmp::PartialOrd
impl<T: Clone + std::cmp::PartialOrd> Point<T> {
  fn largest(&self) -> T {
    if self.x > self.y {
      self.x.clone()
    }
    else {
      self.y.clone()
    }
  }
}

impl Point<f32> {
  /**
   * 点到原点(0,0)的距离
   */
  fn get_distance_from_origin(&self) -> f32 {
    (self.x.powi(2) + self.y.powi(2)).sqrt()
  }
}

struct Line<T> {
  from: T,
  to: T,
}

impl Line<Point<f32>> {
  /**
   * 两点间的距离
   */
  fn get_two_point_distance(&self) -> f32 {
    ((self.to.x - self.from.x).powi(2) + (self.to.y - self.from.y).powi(2)).sqrt()
  }
}

fn main() {
  let p1: Point<f32> = Point { x: 10.0, y: 20.0 };
  println!("{:?}", p1.largest());
  println!("{:?}", p1.get_distance_from_origin());
  let p2 = Point { x: 12.0, y: 24.0 };
  let line = Line { from: p1, to: p2 };
  println!("{:?}", line.get_two_point_distance());
}

 

posted @ 2022-12-24 14:18  樊顺  阅读(24)  评论(0编辑  收藏  举报