Both sides previous revision Previous revision Next revision | Previous revision |
programming:rust [2020/12/13 18:15] – [Traits] mh | programming:rust [2021/05/25 22:07] (current) – [Enums] mh |
---|
=== 'match' workflow === | === 'match' workflow === |
| |
In general, ''Option<T>'' is used when you want code that will handle each variant. The ''match'' expression is a control flow construct that does just this when used with enums: it will run different code depending on which variant of the enum it has, and that code can use the data inside the matching value. | In general, we use an ''Option<T>'' when we want to handle all the cases. The ''match'' expression is a control flow construct that does just this when used with enums: it will run different code depending on which variant of the enum it has, and that code can use the data inside the matching value. |
| |
Combining ''match'' and ''enum'' is useful in many situations: ''match'' against an ''enum'', bind a variable to the data inside, and then execute code based on it. | Combining ''match'' and ''enum'' is useful in many situations: ''match'' against an ''enum'', bind a variable to the data inside, and then execute code based on it. |
</code> | </code> |
| |
Each type implementing the ''Summary'' trait must define it's own custom behavior for the body of the ''summarize'' method. The compiler will enforce this. | Each type implementing the ''Summary'' trait must define it's own custom behavior for the body of the ''summarize'' method. The compiler will enforce this. Note that instead of a '';'' semicolon a default behavior could be set on the trait declaration within ''{}'' curly brackets. |
| |
To implement a trait on a type : | To implement a trait on a type : |
} | } |
</code> | </code> |
| |
| If the trait had a default behavior, this implementation will override it. |
| |
| Default implementations can also call other methods in the same trait, even if those other methods don't have a default implementation. |
| |
| === Traits as Parameters === |
| |
| Traits can be used to define functions that accept many different types who all implement a certain trait. The function is defined using that trait as a parameter, instead of concrete types. [[https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters|Check here]] for more info. |
| |
| === Blanket implementations === |
| |
| They are extensively used in the Rust Standard librarby and allow implementing a trait for any type that implements another trait. [[https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods|More info]] |
| |
| ==== Lifetimes ==== |
===== Misc ===== | ===== Misc ===== |
| |