mirror of
https://github.com/nkbai/book.git
synced 2026-09-03 21:22:46 +08:00
Merge #224
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>
This commit is contained in:
@@ -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.
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user