如何实现一个在整数上参数化的Rust构造函数?

时间:2018-01-02 21:47:02

标签: rust

我想构建一个在整数上参数化的对象。尝试以下方法:

struct Alpha<T> {
    num: T,
}

impl<T: Integer> Alpha<T> {
    fn new() -> Alpha<T> {
        Alpha { num: 0 }
    }
}

并收到错误:

11 |         Alpha { num: 0 }
   |                      ^ expected type parameter, found integral variable

代码为here。怎么了?

1 个答案:

答案 0 :(得分:1)

  

出了什么问题?

这是:

struct Foo;
impl Integer for Foo { … }
Alpha::<Foo>::new() // This should work as `Foo: Integer` and that's
                    // the only condition on `Alpha::new`.
                    // But it would need to create a instance
                    // of `Foo` from `0`.
                    // But the compiler has no idea how to do that!

num::Integer隐含num::Zeroyou can just use that

impl<T: Integer> Alpha<T> {
    fn new() -> Alpha<T> {
        Alpha { num: Zero::zero() }
    }
}