Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 40 ยท Types and Dispatch

Structs and Custom Types

Define your own Julia types with struct and mutable struct, write outer and inner constructors, customize show, and use Base.@kwdef for keyword defaults.

Built-in types only get you so far. A weather station, a bank account or a 2D point deserves its own type, with named fields and its own behavior. In Julia you create such a type with struct. A struct is a plain bundle of named fields: there are no classes with methods inside, because behavior lives in functions that dispatch on the type.

This lesson covers immutable and mutable structs, constructors (including validation), printing with show, and keyword-friendly defaults with Base.@kwdef. The Julia code is read-only on this site; the runnable examples are Python stand-ins that show the same ideas with dataclasses.

Your first struct

JULIA
struct Point
    x::Float64
    y::Float64
end

p = Point(1.0, 2.5)
p.x                  # 1.0
p.y                  # 2.5
typeof(p)            # Point
fieldnames(Point)    # (:x, :y)

Julia generates a constructor with one argument per field, in order. Values are converted to the field type when possible, so Point(1, 2) stores 1.0 and 2.0. If the conversion is lossy, you get an error: Point(1.5, "a") fails with a MethodError, because a string cannot become a Float64.

Fields without a type annotation are allowed and default to Any, but typed fields are what let the compiler lay out the struct compactly and generate fast code. Prefer concrete field types, or use type parameters when you need flexibility.

Immutable by default

A plain struct is immutable: after creation you cannot assign to its fields.

JULIA
p = Point(1.0, 2.5)
p.x = 5.0
# ERROR: setfield!: immutable struct of type Point cannot be changed

That sounds restrictive, but it is a feature. Immutable structs can be stored inline in arrays, passed in registers, and shared safely, which is why numbers, ranges and small geometric types are all immutable. To "change" a point, you build a new one:

JULIA
shifted = Point(p.x + 1, p.y)

When you really need to change fields in place, use mutable struct:

JULIA
mutable struct Counter
    count::Int
    label::String
end

c = Counter(0, "clicks")
c.count += 1
c.count              # 1

Mutable structs live on the heap and are compared by identity: two separate Counter(0, "a") values are not ===, even though their fields match. Immutable structs compare by content with ===. Use mutable structs for objects with a life of their own (a connection, a game state) and immutable ones for values.

Choose a struct kind

struct Immutable. Fields never change after creation.
mutable struct Fields can be assigned. Lives on the heap.

Start immutable. Reach for mutable only when you need it.

1 / 2

Custom constructors

The generated constructor is often enough, but sometimes you want a convenient shortcut or a validity check. Julia has two kinds of constructors.

An outer constructor is just a method added to the type's name. It cannot create an object directly; it calls another constructor:

JULIA
Point(x) = Point(x, x)       # Point(3.0) is the point (3.0, 3.0)
Point() = Point(0.0, 0.0)    # the origin

An inner constructor is written inside the struct block. It replaces the default constructor and builds the object with the special function new. This is how you enforce an invariant, because there is then no way to create an invalid object:

JULIA
struct Temperature
    celsius::Float64

    function Temperature(celsius)
        celsius >= -273.15 || throw(ArgumentError("below absolute zero: $celsius"))
        return new(celsius)
    end
end

Temperature(21.5)      # works
Temperature(-300)      # ERROR: ArgumentError: below absolute zero: -300

Once you define an inner constructor, the default constructors are no longer generated. Anything else must go through your validation, which is the point. Outer constructors then add conveniences on top.

Controlling how a struct prints

By default Julia prints a struct as its name and fields, such as Point(1.0, 2.5). You customize this by adding a method to Base.show:

JULIA
function Base.show(io::IO, p::Point)
    print(io, "(", p.x, ", ", p.y, ")")
end

p = Point(1.0, 2.5)
println(p)             # (1.0, 2.5)

Note the Base. prefix: you are extending a function that belongs to Base, not creating a new function. The argument io is where output goes, so your method also works when printing to a file or a string. This idea of extending existing functions with methods for your own type is central to Julia, and you will use it again in Interfaces and Iteration Protocols.

Keyword constructors with Base.@kwdef

Structs with many fields are awkward to build positionally. Base.@kwdef is a macro that generates a keyword constructor and lets each field have a default:

JULIA
Base.@kwdef struct ServerConfig
    host::String = "localhost"
    port::Int = 8080
    debug::Bool = false
end

ServerConfig()                       # all defaults
ServerConfig(port = 9000)            # override one field
ServerConfig(host = "example.org", debug = true)

It also works with mutable struct. The keyword names document the call site, and adding a new field later with a default does not break existing code.

Structs and the type hierarchy

A struct can declare a supertype, joining the hierarchy from The Type System:

JULIA
abstract type Shape end

struct Circle <: Shape
    r::Float64
end

struct Rect <: Shape
    w::Float64
    h::Float64
end

Subtyping in Julia only links types: it shares interface and dispatch targets, not fields. A concrete struct cannot inherit fields from another struct. If two shapes both need a name, repeat the field, or use composition by storing a struct inside another.

Structs in Python

Python's frozen dataclass is a close cousin of an immutable struct, and a normal dataclass of a mutable struct. This stand-in shows both, including the validation that an inner constructor performs.

Python Immutable vs mutable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note that Python does not convert Point(1, 2) to floats; Julia does, because field types are enforced.

Python Validation and keyword defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Julia the validation is stricter: with an inner constructor there is no way around it. In Python, object.__new__ and copy tricks can still skip __post_init__.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you run p.x = 5.0 for an instance of a plain struct Point?

    Structs are immutable by default. Use mutable struct when fields must change, or build a new value instead.
  2. 2. Which keyword creates an object inside an inner constructor?

    Inside an inner constructor the special function new builds the object from field values. Outside the struct block you call the type name instead.
  3. 3. Why would you write an inner constructor?

    Defining an inner constructor removes the default constructors, so every object has to pass through your checks.
  4. 4. What does Base.@kwdef add to a struct?

    The macro generates a constructor that takes the fields as keyword arguments and uses the = default values you wrote.
  5. 5. How do you customize how a struct prints?

    show is a function in Base. You extend it with a method for your own type, and Julia uses it whenever the value is displayed.

Summary

  • struct Name ... end defines an immutable composite type; mutable struct allows field assignment.
  • Fields are accessed with dot syntax and should usually have concrete types.
  • Outer constructors add conveniences; inner constructors using new enforce invariants and replace the default.
  • Extend Base.show to control printing for your type.
  • Base.@kwdef generates keyword constructors with default values.
  • Structs can subtype an abstract type for dispatch, but they never inherit fields.

Next: use these types as the foundation of Julia's defining feature in Multiple Dispatch.