Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 26 additions & 24 deletions src/static-guarantees/typestate-programming.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,42 @@ The concept of [typestates] describes the encoding of information about the curr
[Builder Pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html

```rust
#[derive(Debug)]
struct Foo {
inner: u32,
}
pub mod foo_module {
#[derive(Debug)]
pub struct Foo {
inner: u32,
}

struct FooBuilder {
a: u32,
b: u32,
}
pub struct FooBuilder {
a: u32,
b: u32,
}

impl FooBuilder {
pub fn new(starter: u32) -> Self {
Self {
a: starter,
b: starter,
impl FooBuilder {
pub fn new(starter: u32) -> Self {
Self {
a: starter,
b: starter,
}
}
}

pub fn double_a(self) -> Self {
Self {
a: self.a * 2,
b: self.b,
pub fn double_a(self) -> Self {
Self {
a: self.a * 2,
b: self.b,
}
}
}

pub fn into_foo(self) -> Foo {
Foo {
inner: self.a + self.b,
pub fn into_foo(self) -> Foo {
Foo {
inner: self.a + self.b,
}
}
}
}

fn main() {
let x = FooBuilder::new(10)
let x = foo_module::FooBuilder::new(10)
.double_a()
.into_foo();

Expand All @@ -60,4 +62,4 @@ Because Rust has a [Strong Type System], there is no easy way to magically creat

[Strong Type System]: https://en.wikipedia.org/wiki/Strong_and_weak_typing

This allows us to represent the states of our system as types, and to include the necessary actions for state transitions into the methods that exchange one type for another. By creating a `FooBuilder`, and exchanging it for a `Foo` object, we have walked through the steps of a basic state machine.
This allows us to represent the states of our system as types, and to include the necessary actions for state transitions into the methods that exchange one type for another. By creating a `FooBuilder`, and exchanging it for a `Foo` object, we have walked through the steps of a basic state machine.