创建新的通用结构的正确方法是什么?

What is the proper way to create a new generic struct?

我正在尝试创建一个可以初始化为 T 类型的通用结构。它看起来像这样:

pub struct MyStruct<T> {
    test_field: Option<T>,
    name: String,
    age: i32,
}

impl MyStruct<T> {
    fn new(new_age: i32, new_name: String) -> MyStruct<T> {
        MyStruct<T> {
            test_field: None,
            age: new_age,
            name: new_name,
        }
    }
}

这似乎不起作用。在其他错误中,我得到:

error: chained comparison operators require parentheses
 --> src/lib.rs:9:17
  |
9 |         MyStruct<T> {
  |                 ^^^^^
  |

强烈推荐阅读The Rust Programming Language. It covers basics like this, and the Rust team spent a lot of time to make it good! Specifically, the section on generics可能会对这里有所帮助。

实例化结构时不需要使用<T>。将推断 T 的类型。您需要声明 Timpl 块上的泛型类型:

struct MyStruct<T> {
    test_field: Option<T>,
    name: String,
    age: i32,
}

impl<T> MyStruct<T> {
//  ^^^
    fn new(new_age: i32, new_name: String) -> MyStruct<T> {
        MyStruct {
            test_field: None,
            age: new_age,
            name: new_name,
        }
    }
}

一样,您可以选择使用 turbofish 语法 (::<>):

来指定类型参数
MyStruct::<T> {
//      ^^^^^
    test_field: None,
    age: new_age,
    name: new_name,
}

现代编译器版本现在实际上告诉你:

  = help: use `::<...>` instead of `<...>` if you meant to specify type arguments
  = help: or use `(...)` if you meant to specify fn arguments

我只在类型不明确时见过这样的情况,这种情况很少发生。