Traits as Function Parameters and Return Types
Still very similar to Java interfaces!
Github: https://github.com/caveofprogramming/rust/
Using Traits in Return Types
I created a file called book.rs and put a struct in it:
The struct and its fields all have to be public if I want to use it outside of the file it’s in.
To make the Rust compiler process this file, I need a mod
statement in main.rs to tell Rust about the file.
I also want to be able to use the new Book type I’ve created in main.rs, so I also add a use
statement:
I want to create a couple of traits that my book will implement, so I put those in a file I called details.rs. Here is the complete details.rs:
I load details.rs by adding a mod statement to main.rs:
Now in book.rs I can say that Book
implements these traits, by importing the traits and then adding implementations. Here is the complete book.rs. Notice I had to import the traits via absolute paths, not relative paths.
Now in main.rs I can define a function that returns an object that implements both traits:
I can then use this to obtain a book object, and since I know it must have methods author()
and title()
, I can use those to print details. Here is the complete main.rs:
Traits as Function Parameters
A very similar syntax can be used to specify that a function argument must implement certain traits, again using the impl
keyword.
This function accepts a reference to an object that implements the Author
and Title
traits. If only one interface needs to be implemented, of course neither the +
nor the brackets after the &
are needed.
This is apparently syntactic sugar for a slightly different syntax:
There is another syntax which is designed to be helpful if you need to specify lots of interfaces or have lots of generic parameter types: