State Machine -> Does Rust always optimize same-size struct moves?

I wanted to know if the Rust compiler would optimize the following state machine pattern, as inspired by this blog post .

Please let me know if this is zero cost, because it could help me to enforce compile time constraints while keeping the same overall data structure

struct StateA {
   foo: RefToSomeObject

struct StateB {
  bar: RefToSomeObject

struct Request<S> {
  data: String,
  state: S

// noting that that StateA and StateB have same exact size
// would the following move be zero cost?
// Request<StateA> -> Request<StateB>

let a = A {
  data: String::from("a"),
  state: StateA { foo: CoolRef }

// Do some random function calls in the middle

let b = B {
  state: StateB { bar: }

Always? Probably not, but I think it is pretty likely to do so in many cases.

1 Like

I was about to say yes, but:

Thanks for the answers. Seems that I shouldn't count on it happening automatically if I am doing this in a performance critical loop.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.