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

后端 未结 1 863
说谎
说谎 2021-01-13 01:45

I\'m trying to make a generic struct that can be initialized to something of type T. It looks like this:

pub struct MyStruct {
    test         


        
相关标签:
1条回答
  • 2021-01-13 01:56

    I highly recommend reading 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 would probably have helped here.

    You don't need to use <T> when instantiating the struct. The type for T will be inferred. You will need to declare that T is a generic type on the impl block:

    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,
            }
        }
    }
    

    As DK. points out, you could choose to specify the type parameter using the turbofish syntax (::<>):

    MyStruct::<T> {
    //      ^^^^^
        test_field: None,
        age: new_age,
        name: new_name,
    }
    

    Modern compiler versions actually tell you this now:

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

    I've only ever seen something like this when the types are ambiguous, which doesn't happen very often.

    0 讨论(0)
提交回复
热议问题