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