README.md

Why do we need to use dyn when referring to State?

At compile time the compiler doesn’t know what value the state will have. Therefore you will get an error on compiling if you don’t force the compiler to use dynamic dispatch. Without dyn (dynamic dispatch) the compiler wants to precompile only one State. By using dyn, we force the compiler to use dynamic dispatch, which means it will not optimize and compile only one state. The compiler will compile all possible states and create a vtable which refers to all the available states.

What does the as_ref() method do?

If you directly use unwrap, you will get to own the state, but you only need an immutable read, therefore you can use as_ref(), which converts an Option into an Option<&T>, and then you can unwrap and get a reference to the value instead of ownwership.

What does take() do?

take() takes the value (ownership) and places a None it it’s place. The state cannot be empty, it can either be None or some State.

Trade-offs of the State Pattern

One downside of the state pattern is that, because the states implement the transitions between states, some states are coupled to each other. If we add another state between 2 existing states, we would need to change the code in those states as well.

Another downside is that we’ve duplicated some logic.

Описание

just an example of using trait objects

Конвейеры
0 успешных
0 с ошибкой