Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic struct field with trait bounds [duplicate]

Tags:

rust

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?

like image 696
German Lashevich Avatar asked Nov 24 '25 12:11

German Lashevich


1 Answers

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,
    }
}
like image 141
SirDarius Avatar answered Nov 28 '25 15:11

SirDarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!