I have a function taking impl MyTrait
as parameter:
fn create_struct(t: impl MyTrait) -> MyStruct {
MyStruct {
field: t
}
}
What is the type of field
? As we can't use impl MyTrait
in a struct field
I have a function taking impl MyTrait
as parameter:
fn create_struct(t: impl MyTrait) -> MyStruct {
MyStruct {
field: t
}
}
What is the type of field
? As we can't use impl MyTrait
in a struct field
You would need a generic struct.
struct MyStruct<T> {
field: T,
}
fn create_struct<T: MyTrait>(t: T) -> MyStruct<T> {
MyStruct { field: t }
}
Yes of course, just (re)read this part of the book: Traits: Defining Shared Behavior - The Rust Programming Language
it's just syntax sugar for generic so yes, I need generic for my struct too.
Ta!
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.