Skip to content

Instantly share code, notes, and snippets.

@CoolOppo
Created February 8, 2019 02:54
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 CoolOppo/89f4bb2dc60caa15f3f51dd218135105 to your computer and use it in GitHub Desktop.
Save CoolOppo/89f4bb2dc60caa15f3f51dd218135105 to your computer and use it in GitHub Desktop.
Rust clamp function for most types
trait Clamp<T> {
fn clamp(self, min: T, max: T) -> T;
}
impl<T> Clamp<T> for T
where
T: PartialOrd + Copy,
{
fn clamp(self, min: T, max: T) -> T {
if self > max {
max
} else if self < min {
min
} else {
self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment