hd-lang

Tour · 16 of 25

A trait is a checked contract: leave out a method and the type doesn't compile

A trait names the methods a type must have, such as an email that can give its subject and its body. send_all works for every type that implements Email and needs nothing else from it. A type opts in with impl Email for ..., and the compiler checks that the impl has every method, with the trait's signature. A new kind of email that forgets its subject is caught when you build it, not when a customer gets a blank message. Methods outside a trait go in a plain impl Type: block.

Run: Ctrl+Enter · Pages: Alt+← Alt+→