5

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?

2 Answers 2

5

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!

Sign up to request clarification or add additional context in comments.

Comments

4

The traits are usually uppercase. In this case it is Ord. See if that helps.

1 Comment

You'll also need a trait to let you add numbers. Unless it's changed since I last saw it, I think you want the Num trait. You might also need to call from_int to get your 1 literal into the correct type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.