38

I'd like to use a trait to bound a generic type, like this hypothetical HasSQRT:

fn some_generic_function<T>(input: &T)
where
    T: HasSQRT,
{
    // ...
    input.sqrt()
    // ...
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Hossein Noroozpour
  • 1,091
  • 1
  • 13
  • 26

1 Answers1

31

You can use num or num-traits crates and bound your generic function type with num::Float, num::Integer or whatever relevant trait:

use num::Float; // 0.2.1

fn main() {
    let f1: f32 = 2.0;
    let f2: f64 = 3.0;
    let i1: i32 = 3;

    println!("{:?}", sqrt(f1));
    println!("{:?}", sqrt(f2));
    println!("{:?}", sqrt(i1)); // error
}

fn sqrt<T: Float>(input: T) -> T {
    input.sqrt()
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
evilone
  • 22,410
  • 7
  • 80
  • 107
  • 29
    @HosseinNoroozpour use dependencies. Rust is unlike many other languages in that package management is built in and strongly embraced. The canonical example is random number generation, which is provided in a crate and not the standard library. – Shepmaster May 18 '16 at 11:24
  • 1
    @HosseinNoroozpour It is understandable to desire minimizing dependencies, but as Shepmaster said, Rust makes dependency management convenient to encourage people to use them. Plus, the `num` crate is very well maintained, it will not be abandoned. – This company is turning evil. May 19 '16 at 01:21
  • 4
    @Kroltan I'm coming from C++ background, in there adding every dependency was a scary decision. I can guess only those libraries that are bound to C libraries are the ones I should avoid to add, am I correct? – Hossein Noroozpour May 19 '16 at 05:27
  • 1
    @HosseinNoroozpour I'd avoid dependencies that are not in pure stable rust. – Rainb Dec 14 '22 at 17:30