Structs and Methods
Structs, tuple and unit structs, `impl` blocks, the `self` receiver forms, associated functions and `derive`.
11 questions
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
{:?}to print any struct, asconsole.logdoes in JavaScript: a struct getsDebugonly from#[derive(Debug)]or a manual impl, so here it is error E0277. - ✗Expecting a panic at run time: the trait behind each placeholder is checked while building, so the program never runs.
Follow-up questions
- →What does the program print once
#[derive(Debug)]is added abovestruct P? - →Why does
{}withpitself still fail after#[derive(Debug)]is added?
JuniorTheoryCommonWhat does #[derive] generate, which traits can it derive, and why not Display?
What does #[derive] generate, which traits can it derive, and why not Display?
It writes a trait impl at compile time, field by field, so every field needs the trait. Derivable: Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord. Display is user-facing, so only the author can shape it.
Common mistakes
- ✗Believing
deriveworks through run-time reflection, when it generates code at compile time - ✗Expecting a derive to compile when a field lacks the trait, such as
Copywith aStringfield - ✗Looking for
#[derive(Display)], which std does not provide
Follow-up questions
- →Why does
#[derive(Clone, Copy)]fail on a struct with aStringfield? - →How do you implement
Displayby hand for aPoint { x, y }that prints(x, y)?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting the call to work because the dot adds
&muton its own: that borrow still needs a variable declaredlet mut c, or the call is error E0596. - ✗Expecting a panic at run time: borrows are checked while building, so the compiler rejects
c.inc()and no program is produced.
Follow-up questions
- →Which one-word change makes the program compile, and why does it work?
- →Would the call compile if
inctook&self, and couldincstill changen?
JuniorTheoryCommonWhat do self, &self, &mut self and Self mean in impl, and how is new called?
What do self, &self, &mut self and Self mean in impl, and how is new called?
&self borrows the value to read it, &mut self borrows it to change fields, and self takes it over, so the caller loses it. Self names the type of the impl. A function without self is associated and is called by path: Point::new(1, 2).
Common mistakes
- ✗Thinking a
selfmethod works on a copy, when it moves the value out of the caller - ✗Confusing
Self, the type of theimpl, withself, the value the method was called on - ✗Treating
newas a constructor keyword, although it is an ordinary associated function
Follow-up questions
- →Why is
&selfthe usual choice, and when is takingselfby value the right call? - →Why does
rect.area()compile without writing&rectwhenareatakes&self?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
5 2, as with aconstobject in JavaScript: in Rustmutcovers the whole variable, so withoutlet mut pno field ofpcan be assigned (E0594). - ✗Expecting a panic at run time: mutability is checked while building, so the compiler rejects
p.x = 5and no program is produced.
Follow-up questions
- →What is the smallest change that makes this program print
5 2? - →Can you make only the field
xmutable whileystays read-only?
JuniorTheoryCommonHow do named, tuple and unit structs differ, and when do you use each?
How do named, tuple and unit structs differ, and when do you use each?
Named: struct User { age: u32 }, built with every field and read as u.age; the default. Tuple: struct Meters(f64), built like a call and read as .0; for one or two fields, e.g. a newtype. Unit: struct Marker;, 0 bytes, a type with no data.
Common mistakes
- ✗Treating a tuple struct as an alias of its tuple, though
Meters(f64)is a distinct type - ✗Expecting the fields left out of a struct literal to get default values
- ✗Confusing a unit struct with
(), although everystruct Marker;declares a new type
Follow-up questions
- →Why does
struct Meters(f64)protect against mix-ups thattype Meters = f64does not? - →How do you unpack a tuple struct into separate variables with one
let?
MiddleTheoryCommonWhy store a String, not a &str, in a struct field by default?
Why store a String, not a &str, in a struct field by default?
A String field keeps the struct self-contained, free to be returned or kept anywhere. A &str field adds a lifetime, User<'a>: no value outlives the text, and all users of a long-lived type carry 'a. Borrow only in short views, e.g. a parser.
Common mistakes
- ✗Choosing
&strfor speed without noticing the lifetime parameter it forces on the struct and on every user of it - ✗Believing a reference field must be
&'static str, when a named lifetime such as'aworks - ✗Thinking the compiler extends the borrowed data's life to match the struct
Follow-up questions
- →What does
struct Parser<'a> { input: &'a str }promise, and when does it pay off? - →When is
Cow<'a, str>a better field type than bothStringand&str?
JuniorCodeOccasionalWrite a struct with an enum field, a method and a trait implementation
Write a struct with an enum field, a method and a trait implementation
Declare enum Priority { Low, High } and struct Task { title: String, priority: Priority }; impl Task adds new returning Self and is_urgent(&self), a match on self.priority; and impl fmt::Display for Task prints [high] title.
Common mistakes
- ✗Expecting
#[derive(Display)]to exist instead of writingimpl fmt::Display - ✗Writing methods inside the
structbody, as in a class, instead of in animplblock - ✗Storing
&strin the field without a lifetime instead of an ownedString
Follow-up questions
- →How would you let
Taskprint with{:?}as well as with{}? - →Why does
is_urgenttake&selfrather thanself?
JuniorTheoryOccasionalWhat does the program print?
What does the program print?
5 2
Open full question →Common mistakes
- ✗Expecting
1 2:..p1takes only the fields the literal does not list, so the explicitx: 5stays and onlyycomes fromp1. - ✗Expecting
5 0or an error for the missingy:..p1fills every unlisted field fromp1, and a field never gets a default value on its own.
Follow-up questions
- →What happens to
p1if the fields taken through..p1areStrings? - →Where in the literal must
..p1stand, and can a comma follow it?
MiddleTheoryOccasionalWhat does each common derive require of the fields, and does PartialEq give Eq?
What does each common derive require of the fields, and does PartialEq give Eq?
Every field must have the derived trait: Clone for Clone, same for Debug, Hash, Default; Copy also needs Clone. Eq is derived apart from PartialEq and needs Eq fields, so PartialEq gives no Eq, and an f64 field rules it out.
Common mistakes
- ✗Assuming
#[derive(PartialEq)]also providesEq - ✗Expecting
#[derive(Clone, Copy)]to compile on a struct with aStringfield - ✗Thinking a derive quietly skips the fields that lack the trait
Follow-up questions
- →Why can a struct with an
f64field not be aHashMapkey through derives alone? - →What breaks if
PartialEqis written by hand whileHashis still derived?
MiddleDesignOccasionalAn order service passes a user id and an order id around as two plain u64 values, and fn cancel(user_id: u64, order_id: u64) has twice been called in production with the arguments swapped. Redesign the id types so that the compiler rejects a swapped call. Constraints: ids are used as HashMap keys, compared with ==, printed in logs and copied freely; adding two ids together, or passing a bare number where an id is expected, must not compile; the change must add no run-time cost in memory or speed; raw u64 values appear only at the database boundary. Describe the types you introduce, what they cost at run time, and which traits you derive or implement for them.
An order service passes a user id and an order id around as two plain u64 values, and fn cancel(user_id: u64, order_id: u64) has twice been called in production with the arguments swapped. Redesign the id types so that the compiler rejects a swapped call. Constraints: ids are used as HashMap keys, compared with ==, printed in logs and copied freely; adding two ids together, or passing a bare number where an id is expected, must not compile; the change must add no run-time cost in memory or speed; raw u64 values appear only at the database boundary. Describe the types you introduce, what they cost at run time, and which traits you derive or implement for them.
Give each id its own tuple struct, struct UserId(u64); and struct OrderId(u64);, so a swap is E0308. A wrapper is the size of u64, checked only at compile time. Derive Clone, Copy, PartialEq, Eq, Hash, Debug, implement Display, skip Add.
Common mistakes
- ✗Using
type UserId = u64, an alias the compiler treats as plainu64, so swaps still compile - ✗Assuming a wrapper struct costs memory or speed, though it has the layout of its single field
- ✗Adding
Derefor arithmetic to the wrapper, which brings back the mix-ups it was meant to stop
Follow-up questions
- →What does the layout attribute
#[repr(transparent)]add toUserIdbeyond what Rust already does? - →Where would you turn a raw
u64into aUserId, and through which std trait?