0

I am trying to write a generic function. I have the following code:

struct Car {
    id: u8,
    wheels: u8,
    seatbelt: bool,
}

struct Motorcycle {
    id: u8,
    wheels: u8,
    helmet: bool,

trait Vehicle {}
impl Vehicle for Car {}
impl Vehicle for Motorcycle {}

fn vehicle_info<T>(vehicle: T) 
where
    T: Vehicle,
{
    println!("{} {}", vehicle.id, vehicle.wheels)
}

The compiler gives me error: no field id on type T. Now the question is how do I promise to the compiler in the trait that all structs passed into the function have these certain fields?

xosxos
  • 167
  • 1
  • 6
  • 1
    Take the time to read [the documentation](https://doc.rust-lang.org/book/ch10-02-traits.html). When you declare `T: Vehicle` this means that you can use any data of type `T` only through what was declared *inside* the `Vehicle` trait. Here `Vehicle` is empty so you cannot do anything with it. – prog-fh Nov 04 '20 at 20:04

1 Answers1

1

In Rust, traits cannot have fields for now. You can provide access to a field from a trait with a method (commonly referred to as getters):

trait Vehicle {
    fn get_id(&self) -> u8;
    fn get_wheels(&self) -> u8;
}

You can implement the trait by simply returning the associated field:

impl Vehicle for Car {
    fn get_id(&self) -> u8 {
        self.id
    }
    
    fn get_wheels(&self) -> u8 {
        self.wheels
    }
}

And now you can access the fields of a Vehicle through the getter methods:

fn vehicle_info<T>(vehicle: T) 
where
    T: Vehicle,
{
    println!("{} {}", vehicle.id(), vehicle.wheels())
}
Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54