daily pastebin goal
25%
SHARE
TWEET

[Rust] Using generics in objects

cwchen Sep 8th, 2017 193 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top