'What is typestate?

What does TypeState refer to in respect to language design? I saw it mentioned in some discussions regarding a new language by mozilla called Rust.



Solution 1:[1]

It's basically an extension of types, where you don't just check whether some operation is allowed in general, but in this specific context. All that at compile time.

The original paper is actually quite readable.

Solution 2:[2]

There's a typestate checker written for Java, and Adam Warski's explanatory page gives some useful information. I'm only just figuring this material out myself, but if you are familiar with QuickCheck for Haskell, the application of QuickCheck to monadic state seems similar: categorise the states and explain how they change when they are mutated through the interface.

Solution 3:[3]

Typestate is explained as:

  • leverage type system to encode state changes
  • Implemented by creating a type for each state
    • Use move semantics to invalidate a state
    • Return the next state from the previous state
    • Optionally drop the state(close file, connections,...)
  • Compile time enforcement of logic
struct Data;
struct Signed;

impl Data {
  fn sign(self) -> Signed {
    Signed
  }
}

let data = Data;
let singed = data.sign();

data.sign() // Compile error

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mhd
Solution 2 Charles Stewart
Solution 3 Heartbit