From ba253673bb8ffb68bb349b910eafb5ee5c535c62 Mon Sep 17 00:00:00 2001 From: Logan Hunter Date: Wed, 29 Jan 2020 21:03:51 -0700 Subject: [PATCH] Make typestate initialization notes correct 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. --- .../typestate-programming.md | 54 ++++++++++--------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/src/static-guarantees/typestate-programming.md b/src/static-guarantees/typestate-programming.md index 9f21150..9bd70f4 100644 --- a/src/static-guarantees/typestate-programming.md +++ b/src/static-guarantees/typestate-programming.md @@ -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, -} - -struct FooBuilder { - a: u32, - b: u32, -} - -impl FooBuilder { - pub fn new(starter: u32) -> Self { - Self { - a: starter, - b: starter, - } +pub mod foo_module { + #[derive(Debug)] + pub struct Foo { + inner: u32, } - pub fn double_a(self) -> Self { - Self { - a: self.a * 2, - b: self.b, - } + pub struct FooBuilder { + a: u32, + b: u32, } - pub fn into_foo(self) -> Foo { - Foo { - inner: self.a + self.b, + 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 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(); @@ -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. \ No newline at end of file +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.