Abstractions in Practice · 19 min · free with an account

Phantom Types

Lesson preview · about 30%

Track a compile-time state with no stored value.

Core idea

PhantomData tells the type system that a zero-sized marker matters to ownership or state.

Start with the idea

PhantomData tells the type system that a zero-sized marker matters to ownership or state. It enables APIs where illegal transitions have no callable method, without adding runtime storage.

PhantomData<T> is a zero-sized marker that tells the compiler a type is logically related to T even when it stores no T value. In Job<State>, the state appears only at the type level. Job<Ready> and Job<Running> can have the same runtime fields but expose different methods. A transition can consume one state and return another, so calling a finish method on a job that was never started becomes a compile-time error.

The marker has no runtime payload, but it is not decorative.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery