programming:rust

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Next revisionBoth sides next revision
programming:rust [2020/12/13 18:10] – [Traits] mhprogramming:rust [2020/12/13 18:22] – [Traits] mh
Line 483: Line 483:
 A **trait** tells the Rust compiler about functionality a particular type has and can share with other types. A **trait** tells the Rust compiler about functionality a particular type has and can share with other types.
 </WRAP> </WRAP>
 +
 +=== Defining ===
 +
 +[[https://doc.rust-lang.org/book/ch10-02-traits.html#defining-a-trait|Chapter 10.2]] details how to create a trait like this one :
 +
 +<code rust>
 +pub trait Summary {
 +    fn summarize(&self) -> String;
 +}
 +</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. 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 :
 +
 +<code rust>
 +impl Summary for SomeStruct {
 +    fn summarize(&self) -> String {
 +        //some 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.
 ===== Misc ===== ===== Misc =====
  
  • programming/rust.txt
  • Last modified: 2021/05/25 22:07
  • by mh