I have a function which works to make a linked list of integers:
enum List<T> { Cons(T, ~List<T>), End }
fn range(start: int, end: int) -> ~List<int> {
if start >= end { ~End }
else { ~Cons(start, range(start+1, end)) }
}
However, I want to make a range of any numeric type, including uints, doubles and the like. But this, for example, doesn't work:
fn range<T: ord>(start: T, end: T) -> ~List<T> {
if start >= end { ~End }
else { ~Cons(start, range(start+1, end)) }
}
which produces:
> rustc list.rs
list.rs:3:12: 3:15 error: use of undeclared type name `ord`
list.rs:3 fn range<T: ord>(start: T, end: T) -> ~List<T> {
^~~
error: aborting due to previous error
How can I make a generic function in rust which restricts itself to be callable by "numeric" types? Without having to specifically write the interface myself? I had assumed that there were a number of standard-library traits (such as those listed in section 6.2.1.1 of the manual like eq
, ord
, etc, though now I'm wondering if those are proper "traits" at all) that I could use when declaring generic functions?
The traits are usually uppercase. In this case it is Ord. See if that helps.
In the current master, there is a trait named 'Num' which serves as a general trait for all numeric types. Work has been done recently to unify many of the common math functions to work on this trait rather than u8, f32, etc , specifically.
See https://github.com/mozilla/rust/blob/master/src/libstd/num/num.rs#L26 for the aforementioned Num trait.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With