Using trait constraints
Back in the section on Generic data structures and functions in Chapter 5, Higher Order Functions and Error-Handling, we made a function sqroot
to calculate the square root of a 32-bit floating point number:
// see code in Chapter 5/code/sqrt_match.rs Use std::f32; fn sqroot(r: f32) -> Result<f32, String> { if r < 0.0 { return Err("Number cannot be negative!".to_string()); } Ok(f32::sqrt(r)) }
What if we wanted to calculate the square root of an f64
type number? It would be very unpractical to make a different version of the function for each type. A first attempt would be to just replace an f32
type with a generic type <T>
:
// see code in Chapter 6/code/trait_constraints.rsfn sqroot<T>(r: T) -> Result<T, String> { if r < 0.0 { return Err("Number cannot be negative!".to_string()); } Ok(T::sqrt(r)) }
But Rust does not agree because it doesn't know anything about T
, signaling multiple errors:
...