What are Traits in Rust ?
Understanding Inheritance and Polymorphism in Rust programming using simple and applicable examples.
Inheritance and Polymorphism are non-trivial parts of any Object Oriented Programming. In Rust, traits are used to provide this type of abstraction.
The problem with learning Inheritance and Polymorphism in Rust (in fact, in any OOP ) is that the examples used are usually fruits, animals or cars. Which never seems to explain the application-level use of this type of abstraction.
So I found this cool video by Code to the Moon which my explanation below is based on.
Don’t forget to leave a comment. Your feedback will be really useful to improve my newsletter. Thank you.
Traits using Files Example
So let me try to explain traits in Rust using files. We know that in any Operating system, there are files. These could be differentiated using different extensions such as “.txt”, “.ssh”, “.cpp”, and “.rs”. Although they may represent different types of data they are typically the same (a file to the OS).
In the example below: We have 2 types of files represented as a struct CppFiles and RustFiles. Each has some metadata represented by the elements of the struct, the name element which signifies the name of the file and the ext element which contains the file extension of the file.
The new() method implementation is used to create the respective files. However, it is important to note the print_file_details() method which takes a mutable reference to itself and prints the name and extension of the provided.
This is useful but while printing the file details we must make sure that we use the right type. For eg. in the print_cpp_file() utility function we must provide a CppFile type as an argument and the same goes with print_rust_file() where we provide a RustFile type.
Well now, it’s pretty obvious although CppFile and RustFile are different types they are typically a File. So this means that they can have a common “trait” (common behaviour).
So in the below example, I have included a TxtFile to the program. I defined a FileDetail trait which prints a default message. This trait can be implemented by all the File types.
Now when we call the print_any_file(filename: &dyn FileDetail), we can provide an argument of any file type and it will print file details. If no implementation is provided as in TxtFile here, it will print a default message.
We also have to notice the dyn keyword which is used for dynamic dispatch. This maintains a pointer to the instance and as well the method.
This is a simple example of using Traits in Rust. Hopefully it makes programming much simpler and more efficient.
Follow me on Linkedin: anvayabn
If you wanna check out my projects: Github
Please Like, Share and Subscribe.
Well written and informative!