Rust Fundamentals · 20 XP Pro

Deriving traits

Your own structs start out with almost no abilities: you cannot print them, copy them, or compare them with ==. The #[derive(...)] attribute asks the compiler to generate those abilities for you:

  • Debug lets you print the struct with {:?}, and makes failing assert_eq! show the values.
  • Clone adds a .clone() method that makes a deep copy.
  • PartialEq enables == and !=, comparing field by field.
#[derive(Debug, Clone, PartialEq)]
pub struct Tag {
    pub label: String,
}

let a = Tag { label: String::from("x") };
let b = a.clone();
assert_eq!(a, b);

assert_eq! needs both PartialEq (to compare) and Debug (to report a mismatch), so the derive line is what makes struct tests possible.

Your task

The Point struct is in the starter, but it has no derives yet, so the tests cannot even compile.

  1. Add #[derive(Debug, Clone, PartialEq)] to Point.
  2. Write pub fn translate(p: &Point, dx: i32, dy: i32) -> Point that returns a new point moved by dx and dy, leaving p unchanged.
  3. Write pub fn mirror(p: &Point) -> Point that returns a new point with x and y swapped.

Next lesson →

Sign in to run your code. It's free.