如何实现在整数上参数化的Rust构造函数? [重复]

问题描述 投票:0回答:1

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

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。怎么了?

rust
1个回答
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() }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.