I'm trying to implement a structure with a field of generic type which has trait bounds. I want to have a value of Group.admin to be Printable. It doesn't matter what exactly type it is.
struct Group<T: Printable> {
admin: T,
}
struct Person {
name: String,
}
impl Person {
fn new() -> Person {
Person {
name: String::from("Bob"),
}
}
}
trait Printable {
fn print(&self);
}
impl Printable for Person {
fn print(&self) {
println!("{}", self.name);
}
}
fn group_test<T: Printable>() -> Group<T> {
Group {
admin: Person::new(),
}
}
But the compiler doesn't allow this:
error[E0308]: mismatched types
--> src/lib.rs:27:16
|
27 | admin: Person::new(),
| ^^^^^^^^^^^^^ expected type parameter, found struct `Person`
|
= note: expected type `T`
found type `Person`
I'm not sure what's wrong here. Maybe I have to cast value of Person::new() to <T: Printable> somehow?
The group_test function is not generic, it is supposed to return a Group<T> but instead you return a Group<Person>.
This compiles:
fn group_test() -> Group<Person> {
Group {
admin: Person::new(),
}
}
This would also compile:
fn group_test<T: Printable>(printable: T) -> Group<T> {
Group {
admin: printable,
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With