Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev
Last active November 13, 2018 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewRadev/59098b853ec13f350a07038d7653a18e to your computer and use it in GitHub Desktop.
Save AndrewRadev/59098b853ec13f350a07038d7653a18e to your computer and use it in GitHub Desktop.
Divide successfully or default to zero
trait OrZero {
fn or_zero(self) -> Self;
}
impl OrZero for f64 {
fn or_zero(self) -> Self {
if self.is_normal() { self } else { 0.0 }
}
}
impl OrZero for f32 {
fn or_zero(self) -> Self {
if self.is_normal() { self } else { 0.0 }
}
}
fn main() {
let inf = 3.1 / 0.0;
let nan = 0.0 / 0.0;
println!("{:?} {:?}", inf, nan);
// inf NaN
let inf = (3.1 / 0.0).or_zero();
let nan = (0.0 / 0.0).or_zero();
println!("{:?} {:?}", inf, nan);
// 0.0 0.0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment