如何在Rust中提供通用结构的实现?

时间:2019-02-03 14:47:57

标签: generics struct rust

我有一个采用通用参数MyStruct的结构T: SomeTrait,并且我想为new实现一个MyStruct方法。这有效:

/// Constraint for the type parameter `T` in MyStruct
pub trait SomeTrait: Clone {}

/// The struct that I want to construct with `new`
pub struct MyStruct<T: SomeTrait> {
    value: T,
}

fn new<T: SomeTrait>(t: T) -> MyStruct<T> {
    MyStruct { value: t }
}

fn main() {}

我想将new函数放在这样的impl块中:

impl MyStruct {
    fn new<T: SomeTrait>(t: T) -> MyStruct<T> {
        MyStruct { value: t }
    }
}

但是无法编译为:

error[E0107]: wrong number of type arguments: expected 1, found 0
 --> src/main.rs:9:6
  |
9 | impl MyStruct {
  |      ^^^^^^^^ expected 1 type argument

如果我尝试这样说:

impl MyStruct<T> {
    fn new(t: T) -> MyStruct<T> {
        MyStruct { value: t }
    }
}

错误更改为:

error[E0412]: cannot find type `T` in this scope
 --> src/main.rs:9:15
  |
9 | impl MyStruct<T> {
  |               ^ not found in this scope

如何提供通用结构的实现?我应该将通用参数及其约束放在哪里?

1 个答案:

答案 0 :(得分:3)

类型参数<T: SomeTrait>应该紧跟impl关键字之后:

impl<T: SomeTrait> MyStruct<T> {
    fn new(t: T) -> Self {
        MyStruct { value: t }
    }
}

如果impl<...>中的类型和约束列表过长,则可以使用where语法并单独列出约束:

impl<T> MyStruct<T>
where
    T: SomeTrait,
{
    fn new(t: T) -> Self {
        MyStruct { value: t }
    }
}

请注意Self的用法,它是MyStruct<T>块中可用的impl的快捷方式。


备注

  1. this answer中说明了需要impl<T>的原因。从本质上讲,它可以归结为impl<T> MyStruct<T>impl MyStruct<T>都是有效的,但是含义不同。

  2. new移到impl块中时,应删除多余的类型参数,否则结构的接口将变得不可用,如以下示例所示:

    // trait SomeTrait and struct MyStruct as above
    // [...]
    
    impl<T> MyStruct<T>
    where
        T: SomeTrait,
    {
        fn new<S: SomeTrait>(t: S) -> MyStruct<S> {
            MyStruct { value: t }
        }
    }
    
    impl SomeTrait for u64 {}
    impl SomeTrait for u128 {}
    
    fn main() {
        // just a demo of problematic code, don't do this!
        let a: MyStruct<u128> = MyStruct::<u64>::new::<u128>(1234);
        //                                 ^
        //                                 |
        //        This is an irrelevant type
        //        that cannot be inferred. Not only will the compiler
        //        force you to provide an irrelevant type, it will also
        //        not prevent you from passing incoherent junk as type
        //        argument, as this example demonstrates. This happens 
        //        because `S` and `T` are completely unrelated.
    }