Is there a way to mutate the value in a mutex from StateMachine to StateMachine

I have written a state machine in Rust. I would now like to access it from several threads.

There are methods that change the state of the machine:
e.g. from StateMachine<Init> to StateMachine<Run>

If wrapped in a mutex I receive errors when changing the state (mismatched types).
And when assigning the state machine to a new variable I get an error too (cannot move out of dereference ..).

And I know that StateMachin<Init> is not the same typ as StateMachine<Run> but I am wondering if there is a workaround / solution so that I can use the state pattern in an asynchronous context?

use std::sync::Arc;

use tokio::sync::Mutex;

pub trait State {}

pub struct Init {}
impl State for Init {}

pub struct Run {}
impl State for Run {}

struct StateMachine<S>
where
    S: State,
{
    state: std::marker::PhantomData<S>,
}

impl<S> StateMachine<S>
where
    S: State,
{
    pub fn new() -> StateMachine<Init> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

impl StateMachine<Init> {
    pub fn run(self) -> StateMachine<Run> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

#[tokio::main]
async fn main() {
    let state_machine = Arc::new(Mutex::new(StateMachine::<Init>::new()));
    let locked_machine = state_machine.lock().await;

    //locked_machine = locked_machine.run();
    let new_state = locked_machine.run();
    let state_machine = Arc::new(Mutex::new(new_state));
}

I expect / hope that there is a way to make the mutex accept all StateMachine or that I receive the confirmation that what I want to do is impossible.
I think that I understand why I get the errors but as of now I relly have no idea how to solve it.

I am quite new to Rust and a total newbie to anything async related.
I tried to solve the issue with trait objects but I failed quite hard. I might try that again but I wasn’t able to convert the trait object back to a specific struct e.g. StateMachine.

Another solution would be to implement the state machine as enum and to do the checks at runtime.

Thanks in advance for all help.

New contributor

neffigs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

By definition you can’t store all states of a type-based state machine, because they’re different types.

In order to do that you need to erase the type e.g. add an intermediate enum, or make trait extend Any and add support for dynamic state management.

Another solution would be to implement the state machine as enum and to do the checks at runtime.

Yes, if you always need to store the machine in multiple possible states then a typed state machine doesn’t make sense. A typed state machine either doesn’t escape, or it is stored in different objects / locations in each state.

As suggested by @Masklinn I used a intermediate enum. I did not think of that, tbh. Thanks a lot!

use std::sync::Arc;

use tokio::sync::Mutex;

pub trait State {}

#[derive(Debug)]
pub struct Init {}
impl State for Init {}

#[derive(Debug)]
pub struct Run {}
impl State for Run {}

#[derive(Debug)]
pub struct StateMachine<S>
where
    S: State,
{
    state: std::marker::PhantomData<S>,
}

impl<S> StateMachine<S>
where
    S: State,
{
    pub fn new() -> StateMachine<Init> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

impl StateMachine<Init> {
    pub fn run(self) -> StateMachine<Run> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

#[derive(Debug)]
pub enum OuterStateMachine {
    Init(StateMachine<Init>),
    Run(StateMachine<Run>),
    Invalide,
}

#[tokio::main]
async fn main() {
    let state_machine = Arc::new(Mutex::new(OuterStateMachine::Init(
        StateMachine::<Init>::new(),
    )));
    println!("{:#?}", state_machine);

    {
        let mut locked_machine = state_machine.lock().await;

        let temp = match std::mem::replace(&mut *locked_machine, OuterStateMachine::Invalide) {
            OuterStateMachine::Init(state_machine) => OuterStateMachine::Run(state_machine.run()),
            OuterStateMachine::Run(state_machine) => OuterStateMachine::Run(state_machine),
            OuterStateMachine::Invalide => panic! {},
        };
        *locked_machine = temp;
    }

    println!("{:#?}", state_machine);
}

New contributor

neffigs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Is there a way to mutate the value in a mutex from StateMachine to StateMachine

I have written a state machine in Rust. I would now like to access it from several threads.

There are methods that change the state of the machine:
e.g. from StateMachine<Init> to StateMachine<Run>

If wrapped in a mutex I receive errors when changing the state (mismatched types).
And when assigning the state machine to a new variable I get an error too (cannot move out of dereference ..).

And I know that StateMachin<Init> is not the same typ as StateMachine<Run> but I am wondering if there is a workaround / solution so that I can use the state pattern in an asynchronous context?

use std::sync::Arc;

use tokio::sync::Mutex;

pub trait State {}

pub struct Init {}
impl State for Init {}

pub struct Run {}
impl State for Run {}

struct StateMachine<S>
where
    S: State,
{
    state: std::marker::PhantomData<S>,
}

impl<S> StateMachine<S>
where
    S: State,
{
    pub fn new() -> StateMachine<Init> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

impl StateMachine<Init> {
    pub fn run(self) -> StateMachine<Run> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

#[tokio::main]
async fn main() {
    let state_machine = Arc::new(Mutex::new(StateMachine::<Init>::new()));
    let locked_machine = state_machine.lock().await;

    //locked_machine = locked_machine.run();
    let new_state = locked_machine.run();
    let state_machine = Arc::new(Mutex::new(new_state));
}

I expect / hope that there is a way to make the mutex accept all StateMachine or that I receive the confirmation that what I want to do is impossible.
I think that I understand why I get the errors but as of now I relly have no idea how to solve it.

I am quite new to Rust and a total newbie to anything async related.
I tried to solve the issue with trait objects but I failed quite hard. I might try that again but I wasn’t able to convert the trait object back to a specific struct e.g. StateMachine.

Another solution would be to implement the state machine as enum and to do the checks at runtime.

Thanks in advance for all help.

New contributor

neffigs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

By definition you can’t store all states of a type-based state machine, because they’re different types.

In order to do that you need to erase the type e.g. add an intermediate enum, or make trait extend Any and add support for dynamic state management.

Another solution would be to implement the state machine as enum and to do the checks at runtime.

Yes, if you always need to store the machine in multiple possible states then a typed state machine doesn’t make sense. A typed state machine either doesn’t escape, or it is stored in different objects / locations in each state.

As suggested by @Masklinn I used a intermediate enum. I did not think of that, tbh. Thanks a lot!

use std::sync::Arc;

use tokio::sync::Mutex;

pub trait State {}

#[derive(Debug)]
pub struct Init {}
impl State for Init {}

#[derive(Debug)]
pub struct Run {}
impl State for Run {}

#[derive(Debug)]
pub struct StateMachine<S>
where
    S: State,
{
    state: std::marker::PhantomData<S>,
}

impl<S> StateMachine<S>
where
    S: State,
{
    pub fn new() -> StateMachine<Init> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

impl StateMachine<Init> {
    pub fn run(self) -> StateMachine<Run> {
        StateMachine {
            state: std::marker::PhantomData,
        }
    }
}

#[derive(Debug)]
pub enum OuterStateMachine {
    Init(StateMachine<Init>),
    Run(StateMachine<Run>),
    Invalide,
}

#[tokio::main]
async fn main() {
    let state_machine = Arc::new(Mutex::new(OuterStateMachine::Init(
        StateMachine::<Init>::new(),
    )));
    println!("{:#?}", state_machine);

    {
        let mut locked_machine = state_machine.lock().await;

        let temp = match std::mem::replace(&mut *locked_machine, OuterStateMachine::Invalide) {
            OuterStateMachine::Init(state_machine) => OuterStateMachine::Run(state_machine.run()),
            OuterStateMachine::Run(state_machine) => OuterStateMachine::Run(state_machine),
            OuterStateMachine::Invalide => panic! {},
        };
        *locked_machine = temp;
    }

    println!("{:#?}", state_machine);
}

New contributor

neffigs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật