简体   繁体   English

Rust:使用traits / typeclasses实现通用数字函数

[英]Rust: using traits/typeclasses to implement a generic numeric function

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. 但是,我想制作任何数字类型的范围,包括uints,double等。 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? 如何在rust中创建一个泛型函数,限制自身可以被“数字”类型调用? 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? 我曾假设有许多标准库特征(例如手册第6.2.1.1节中列出的那些特征,如eqord等,但现在我想知道这些特征是否属于正确的“特征”)我可以在声明泛型函数时使用它?

The traits are usually uppercase. 特征通常是大写的。 In this case it is Ord. 在这种情况下,它是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. 在当前的master中,有一个名为'Num'的特征,它作为所有数字类型的一般特征。 Work has been done recently to unify many of the common math functions to work on this trait rather than u8, f32, etc , specifically. 最近已经完成了工作以统一许多常见的数学函数来处理这个特性而不是u8,f32等。

See https://github.com/mozilla/rust/blob/master/src/libstd/num/num.rs#L26 for the aforementioned Num trait. 有关上述Num特征,请参阅https://github.com/mozilla/rust/blob/master/src/libstd/num/num.rs#L26

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM