January 2018
Beginner to intermediate
454 pages
10h 8m
English
Traits are a way to specify that a type must implement some methods and/or some types. They are similar to interfaces in Java. We can implement a trait on a type and we'll be able to use the methods of this trait on this type as long as this trait is imported. This is how we can add methods to types defined in other crates or even the standard library.
Let's write a trait representing a bit set:
trait BitSet { fn clear(&mut self, index: usize); fn is_set(&self, index: usize) -> bool; fn set(&mut self, index: usize); }
Here, we don't write the body of the methods, as they will be defined when we implement this trait for a type.
Now, let's implement this trait for the u64 type:
impl BitSet for u64 { fn clear(&mut self, index: usize