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:
Debuglets you print the struct with{:?}, and makes failingassert_eq!show the values.Cloneadds a.clone()method that makes a deep copy.PartialEqenables==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.
- Add
#[derive(Debug, Clone, PartialEq)]toPoint. - Write
pub fn translate(p: &Point, dx: i32, dy: i32) -> Pointthat returns a new point moved bydxanddy, leavingpunchanged. - Write
pub fn mirror(p: &Point) -> Pointthat returns a new point withxandyswapped.