Hacker News new | past | comments | ask | show | jobs | submit login

  pub fn clamp(self, min: f64, max: f64) -> f64
Rust has generics iirc, so why there's this?



I guess because floats implement PartialOrd, not Ord, and what would you return if one of self, min, and max is non-ordered? Returning an `Option<T>` would usually be inconvenient.

Therefore clamp is implemented on Ord (meaning there's always a value to return), and there's an efficient implementation on floats which can define its behaviour with respect to NaN.

If you want the actual details,

* https://internals.rust-lang.org/t/clamp-function-for-primiti...

* https://github.com/rust-lang/rust/issues/44095


Also the float implementation was chosen to optimize well with SSE, even in presence of NaNs.




Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: