State Pattern in Rust | Rust Language

preview_player
Показать описание
The State pattern is a design pattern used in software development to manage the behaviour of an object when its internal state changes. Instead of having one big chunk of code that handles all possible states, you break it down into smaller pieces of code, each representing a specific state.

- chapters -
00:00 my coding setup
03:07 trait + 3 structs
05:46 impl for State Context
09:16 box dyn
15:04 create a context
18:02 summary

TL,DR;
----------
In the state pattern, there is typically a trait defining state behavior, concrete state structs implementing the trait, and a context or controller managing the transitions between states.

Linux Hosting - VPS server - Webdock
----------------------------------------------------------------

#rustlang #StatePattern #LearnRust
Рекомендации по теме
Комментарии
Автор

I read from the description of your channel that you are learning rust. So I feel allowed to give you some advices on your code :) To me this implementation of state machine is needlessly complicated. Just use a plain enum. You can then assign the new state e.g. like this: `*self = Self::Stop`.

Otherwise I think you got it when it comes to dynamic dispatch. Remember that it is not the only way to use trait as object. You can also use generics and also `impl Trait` in function args and as the return type.

emdeization
Автор

I like the idea, Although really traits are not required for state. Instead you can just have a struct with interior mutability & keep the state in an enum with match statements to define the different behaviors. Anything that requires complexity which would justify Traits could also just be done by using `&dyn Trait` instead of using the extra context struct.

CEbbinghaus
Автор

Why not use generic & PhantomData as the marker?

Nootlink
Автор

That's not a ThinkPad. I'm not watching this.

chudchadanstud