Version: 1.1.0

Structs

A struct is Mojo's unit of data and behavior. Fields and methods are fixed at compile time, which is what makes the layout predictable.

Essentials

  • Declare fields inside the struct body.
  • fn __init__(out self, ...) builds a value.
  • @fieldwise_init writes the obvious initializer for you.
  • Methods take self. Use mut self when the method changes fields.
  • A struct can conform to traits and take compile-time parameters.

Example

@fieldwise_init
struct Point:
    var x: Float64
    var y: Float64

    def length(self) -> Float64:
        return (self.x * self.x + self.y * self.y) ** 0.5

def main():
    var p = Point(3, 4)
    print(p.length())

Keep in mind

Structs are not Python classes. You cannot add fields at runtime, and there is no inheritance hierarchy. Share behavior with traits.