Generic Types and Enums with Associated Values
If you are not familiar with Generic Types and/or Enums with associated values, here is an example of some rust that leverages both.
struct Person<T> {
name: String,
associates: T,
}
enum Associate {
Person(String),
Pet(String, u32),
}
fn main() {
let person_a = Person {
name: "Aye",
associates: "Steve".to_string(),
};
let person_b = Person {
name: "Bea",
associates: vec![
Associate::Person("James".into()),
Associate::Person("Helen".into()),
Associate::Person("Edwardo".into()),
Associate::Person("Maya".into()),
Associate::Pet("Fido".into(), 4),
]
};
}
First we have the definition of Person, this structwill have two fields, their name and their associates. In the definition we have included <T>which is a standard way to say that something about a type is customizable. We set the type of name to Stringand the type of associates to T, this would allow anyone who constructed a Personto say what the type of associates is going to be. So if you wanted the associate field to just be a string because that person has 1 friend, you could do that or you could set the field to be a list of strings if they had more friends.
Next we have the Associateenum, like a standard Cstyle enum we list the cases that this type can be. In addition, we can then associate some data with each case. So the Associate::Personcan hold onto a string, presumably the name of that person and the Associate::Petcan hold onto a string and an integer, the name and number of legs.
inside the main function we have defined 2 people, person_ahas a name and their associate is just 1 name while person_b’s associates are a list of 4 Associate::Personand 1 Associate::Pet.