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
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
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 {
test_field: Option,
name: String,
age: i32,
}
impl MyStruct {
// ^^^
fn new(new_age: i32, new_name: String) -> MyStruct {
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:: {
// ^^^^^
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.