typestar

Structs & traits

22 steps in 5 sets of Mojo.

A struct is how you name a type in Mojo. It has no hidden header, no vtable, and no allocation you did not ask for — the fields you declare are the memory the value occupies, and the compiler lays them out flat. That is what people mean when they call Mojo structs zero-overhead types.

The heart of it is value semantics. Assigning a struct copies it rather than aliasing it, and every argument spells out its intent: read-only by default, mut when the callee edits the caller's value, var plus a trailing caret when ownership moves. Traits then layer shared behavior on top without giving any of that up — a generic function bound by a trait is compiled fresh for each type it meets, so the abstraction disappears before the program runs.

This tour builds one up from bare fields, follows a value through copies and transfers, teaches a struct the operators it deserves, and finishes with traits and the generic code they unlock.

Start this tour

A first struct

Value semantics

Operators

Traits

Encore

  • Bank ledgerAn account struct that guards its own balance and keeps a running history.
  • Shape galleryOne trait, three shapes, and a single generic function that tabulates them all.

The other Mojo tours