Structs
Structs define how data is laid out in memory. Unlike Python classes, Mojo structs have value semantics by default — assigning a struct copies the data, not a reference. Every field must have an explicit type, and the compiler knows the exact size and layout at compile time.
Code
struct Point:
var x: Float64
var y: Float64
fn __init__(out self, x: Float64, y: Float64):
self.x = x
self.y = y
fn distance(self) -> Float64:
return (self.x ** 2 + self.y ** 2) ** 0.5
fn main():
var p = Point(3.0, 4.0)
print(p.distance()) # 5.000000000651334
Value Semantics
When a struct conforms to ImplicitlyCopyable, it is copied on assignment.
There is no hidden reference counting or garbage collection:
struct Point(ImplicitlyCopyable):
var x: Float64
var y: Float64
fn __init__(out self, x: Float64, y: Float64):
self.x = x
self.y = y
fn main():
var a = Point(1.0, 2.0)
var b = a # b is a full copy of a (implicit copy)
b.x = 99.0
print(a.x) # still 1.0 — a is unchanged
Constraint
Define a Vec3 struct with three Float64 fields. Add a dot
method that computes the dot product with another Vec3. Verify that assigning one
Vec3 to another creates an independent copy.
Why It Matters
Value semantics mean no pointer chasing, no cache misses from indirection, and no GC pauses. The compiler can place struct data contiguously on the stack, which is the fastest memory access pattern on modern hardware.