How to use a Generic Struct Example: Rust Programming

In Rust rather than have to create separate structs to accept variables with different data types you can use a generic struct, eg accepting a float…or an integer. Without this, you would need to make one struct to accept u8 and one struct to f64 (if they are the 2 data types you desire).

Let’s see how this works with one generic struct:

// Generic Structs in Rust

struct Car <A,B> {
    cname : String,
    doors : B,
    age : A
}

fn main (){

    let vw = Car{
        cname: String::from("Golf"),
        doors:5,
        age:13
    };

    println!("{:?} {} {:x}", vw.cname, vw.doors, vw.age);

}

By using the < > angled brackets with your own choice of capital letter(s) inside you are specifying a generic data type, use more than one capital letter if you want to accept a mixture of different data types for each variable, eg doors u8 and age f32

struct Car <A,B> {
    cname : String,
    doors : B,
    age : A
}
Rust Generic Struct Example on YouTube