Sub topic 7
Methods that exist only in certain states
This chapter assumes you know generic structs, impl blocks, and PhantomData as a way to use a type parameter without storing a value. It also assumes you can read a compiler error. Here you will see how one struct can offer different methods depending on its type parameter.
Impl blocks can name a concrete type
An impl block does not have to be generic. You can write impl Door<Open> and the methods inside exist only on Door<Open>. A Door<Closed> is a different type, so it never receives them.
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
name: String,
_state: PhantomData<State>,
}
// Shared: available in every state.
impl<State> Door<State> {
fn name(&self) -> &str {
&self.name
}
}
// Only for closed doors.
impl Door<Closed> {
fn new_closed(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn knock(&self) {
println!("knock knock on the {} door", self.name);
}
}
// Only for open doors.
impl Door<Open> {
fn new_open(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn walk_through(&self) {
println!("walking through the {} door", self.name);
}
}
fn main() {
let closed = Door::new_closed("front");
let open = Door::new_open("back");
closed.knock();
open.walk_through();
println!("{} and {}", closed.name(), open.name());
// closed.walk_through(); // error: no method named `walk_through` found for struct `Door<Closed>`
}The program has three kinds of impl block:
impl<State> Door<State>is generic. Its methods work in every state, sonamecan be called on both doors.impl Door<Closed>suppliesknock, which makes sense only for a closed door.impl Door<Open>supplieswalk_through, which makes sense only for an open door.
The constructors also live in state-specific blocks. In Door::new_closed("front"), the compiler finds new_closed only in impl Door<Closed>, so it infers State = Closed without an annotation.
What the compiler says when you get it wrong
If you uncomment the closed.walk_through() line, the build fails with no method named walk_through found for struct Door<Closed> in the current scope. The compiler also notes that the method exists for Door<Open>. Read that note first. It tells you the value is in the wrong state, not that the method is missing.
Overlapping names
Two state-specific blocks can define a method with the same name, because they apply to different types. This is legal:
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
_state: PhantomData<State>,
}
impl Door<Open> {
fn describe(&self) -> &'static str {
"wide open"
}
}
impl Door<Closed> {
fn describe(&self) -> &'static str {
"shut tight"
}
}
fn main() {
let a: Door<Open> = Door { _state: PhantomData };
let b: Door<Closed> = Door { _state: PhantomData };
println!("{} / {}", a.describe(), b.describe());
}A generic block does overlap with every state-specific block. If you added fn describe to impl<State> Door<State> as well, the compiler would reject the program with error E0592, "duplicate definitions". Keep a method either in the shared block or in the state blocks, never both.
Common mistakes
- Putting state-only methods in the generic block. Every state then gets the method, and you lose the compile-time check.
- Forgetting that the fields are shared. All states use the same fields. A field that is valid only in one state needs an
Option, or a different design. The builder chapter returns to this. - Expecting a method to change the state. The methods above only read
self. Moving fromDoor<Closed>toDoor<Open>needs a method that consumesself, which is the next chapter.
Exercise
You have struct Light<S> { _s: PhantomData<S> } with marker types On and Off. You want switch_off_note() callable only on Light<On>, and is_light() callable on any Light. Which impl headers do you write, and what happens if you also define is_light inside impl Light<On>?
Show answer
Write impl<S> Light<S> for is_light, and impl Light<On> for switch_off_note. Defining is_light again in impl Light<On> overlaps with the generic block, so the compiler reports error E0592 (duplicate definitions).