Verifying with traits
We can see enums can empower structs so that they can handle multiple types. This can also be translated for any type of function or data structure. However, this can lead to a lot of repetition. Take, for instance, a User
struct. Users have a core set of values, such as a username and password. However, they could also have extra functionality based on roles. With users, we must check roles before firing certain processes based on the traits that the user has implemented. We can wrap up structs with traits by creating a simple program that defines users and their roles with the following steps:
- We can define our users with the following code:
struct AdminUser {
username: String,
password: String
}
struct User {
username: String,
password: String
}
We can see in the preceding code that the User
and AdminUser
structs have the same fields. For this exercise, we just need two different structs to demonstrate the effect traits have on them. Now that...