Bitpath

Lesson 1 · Unit 03

Traits

Named sets of methods that any type can implement

13 exercisesabout 3 min

What you practise

  • Defining and implementing, derive, Display and Debug, default methods, trait bounds

Try a question from this lesson

Pick one

A Dog and a Robot each have a speak method, and one function should accept either. Rust has no inheritance. What does it use?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

A trait is a set of methods

A trait declares method signatures. impl Trait for Type supplies the bodies for one type.

Unlike a base class, a trait holds no fields, and you can implement your own trait for a type you did not write, even for i32. There is no hierarchy: a type simply has the traits it implements.

Rust
trait Speak {
    fn word(&self) -> String;
}
struct Dog;
impl Speak for Dog {
    fn word(&self) -> String {
        String::from("woof")
    }
}
println!("{}", Dog.word());

Concept

derive

Some traits are so mechanical that the compiler can write the impl. #[derive(...)] above a type asks for them.

Debug gives the {:?} format for developers, Clone gives .clone() and PartialEq gives ==. Display, the {} format meant for users, cannot be derived: only you know how the type should read.

Rust
#[derive(Debug, Clone, PartialEq)]
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };
let q = p.clone();
println!("{:?} {}", q, p == q);

10 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× order the lines
  • 1× match the pairs
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy