Summary - Traits
- Rust course
- Intermediate
- Lesson 6/115
- 5 min
Combine trait and impl to write a Summary trait.
Traits summary
A trait is a contract of behaviour: trait T { fn m(&self); }, implemented with impl T for Type. Methods can have default bodies that can be overridden. Parameters ask for behaviour with &impl T or <X: T>; + combines several traits. The orphan rule: either the trait or the type must be yours. Common traits are implemented automatically with #[derive(..)]: Debug, Clone, PartialEq, Default, Hash.
Ready-made traits with derive
Many standard traits don't need to be written by hand:
#[derive(Debug, Clone, PartialEq, Default)]
struct Nokta {
x: i32,
y: i32,
}
let a = Nokta { x: 1, y: 2 };
let b = a.clone();
println!("{:?} {}", b, a == b); // Nokta { x: 1, y: 2 } true
println!("{:?}", Nokta::default()); // Nokta { x: 0, y: 0 }Copy can only be derived if all fields are Copy, and it's written together with Clone.
Practice Derived traits
Define Nokta { x: i32, y: i32 } with #[derive(Debug, Clone, PartialEq)]. Let a = Nokta { x: 1, y: 2 } and b = a.clone(); print b with {:?} and the result of a == b, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
#[derive(Debug, Clone, PartialEq)]
struct Nokta {
x: i32,
y: i32,
}
fn main() {
let a = Nokta { x: 1, y: 2 };
let b = a.clone();
println!("{:?} {}", b, a == b);
}Expected output
Nokta { x: 1, y: 2 } true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>#[derive(Clone)]</code> give a struct?
- == comparison
- {:?} printing
- A .clone() method copying all fields Correct answer
- Automatic Copy behaviour
Explanation: derive(Clone) generates an implementation calling clone on every field; for that, all fields must be Clone.
2 Add comparison
#[derive(Debug, ____)]
struct Nokta { x: i32, y: i32 }
// a == b artık yazılabilir
#[derive(Debug, PartialEq)]
struct Nokta { x: i32, y: i32 }
// a == b artık yazılabilir
Explanation: PartialEq provides the == and != operators.
3 derive and what it gives
| Term | Meaning |
|---|---|
Debug |
{:?} |
Clone |
.clone() |
PartialEq |
== and != |
Default |
Type::default() |