Advertisement
cwchen

[Rust] Implementing Display trait for Rational

Sep 4th, 2017
3,244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.33 KB | None | 0 0
  1. impl fmt::Display for Rational {
  2.     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  3.         let is_positive = (self.num > 0 && self.denom > 0)
  4.             || (self.num < 0 && self.denom < 0);
  5.  
  6.         let sign = if is_positive { "" } else { "-" };
  7.  
  8.         write!(f, "{}{}/{}", sign, self.num.abs(), self.denom.abs())
  9.     }
  10. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement