Skip to content

Commit

Permalink
Merge #224
Browse files Browse the repository at this point in the history
224: Make typestate initialization notes correct r=therealprof a=Logan-Hunter

As written previously, the note after the initial typestate
programming example saying that there's no direct way to create
a Foo object wasn't quite accurate; in the sample given you
definitely could, since Foo and FooBuilder weren't isolated
into a module. Isolated Foo and FooBuilder into a module to
make the statement correct.

Co-authored-by: Logan Hunter <loganhunter27@gmail.com>
  • Loading branch information
bors[bot] and Logan-Hunter committed Jan 30, 2020
2 parents 0a6af4d + ba25367 commit b2e1092
Showing 1 changed file with 26 additions and 24 deletions.
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.

0 comments on commit b2e1092

Please sign in to comment.