Advertisement
cwchen

[Rust] Using generics in objects

Sep 8th, 2017
975
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.76 KB | None | 0 0
  1. use std::fmt;
  2.  
  3. pub struct Point<T> where T: Copy + fmt::Display {
  4.     x: T,
  5.     y: T
  6. }
  7.  
  8. impl<T> Point<T> where T: Copy + fmt::Display {
  9.     pub fn new(x: T, y: T) -> Point<T> {
  10.         Point::<T>{ x: x, y: y }
  11.     }
  12. }
  13.  
  14. impl<T> Point<T> where T: Copy + fmt::Display {
  15.     pub fn x(&self) -> T {
  16.         self.x
  17.     }
  18. }
  19.  
  20. impl<T> Point<T> where T: Copy + fmt::Display {
  21.     pub fn y(&self) -> T {
  22.         self.y
  23.     }
  24. }
  25.  
  26. impl<T> fmt::Display for Point<T> where T: Copy + fmt::Display {
  27.     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  28.         write!(f, "({}, {})", self.x(), self.y())
  29.     }
  30. }
  31.  
  32. fn main() {
  33.     let p1 = Point::<i32>::new(3, 4);
  34.     println!("{}", p1);
  35.  
  36.     let p2 = Point::<f64>::new(2.4, 3.6);
  37.     println!("{}", p2);
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement