我想构造一个在整数上参数化的对象。尝试以下方法:
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。怎么了?
怎么了?
这是:
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::Zero
,you can just use that:
impl<T: Integer> Alpha<T> {
fn new() -> Alpha<T> {
Alpha { num: Zero::zero() }
}
}