Julia Structs and the Type System
A struct is a custom type that combines multiple related pieces of data into one whole, similar to a struct in C or a class in Python (but without methods).
In Julia, data (structs) and methods (functions) are separate: functions do not belong to any type; instead, an implementation is chosen based on argument types via multiple dispatch, which will be covered in detail in theMethods and Multiple Dispatchchapter in detail.
Defining Structs
Use the struct keyword to define a struct; fields may carry type annotations, otherwise they default to Any:
Example
julia
struct Point
x::
Int
Fields with type annotations
y::
Int
label
Without annotations, the type is Any
end
Calling the type name like a function creates an instance (the type name itself is the constructor):
Example
julia
p = Point
(
3
,
4
,
"A"
)
Point
(
3
,
4
,
"A"
)
julia
typeof
(
p
)
Point
Access fields with dot syntax
julia
p.
x
3
Fields with a declared type automatically perform type conversion
julia
Point
(
1.0
,
2.0
,
"B"
)
1.0 is converted to Int
Point
(
1
,
2
,
"B"
)
An InexactError is thrown when conversion is not possible
julia
Point
(
1.5
,
2
,
"B"
)
ERROR: InexactError:
Int64
(
1.5
)
Note:All struct fields' types must be of the same kind; you cannot store different types for different instances. To make field types flexible, you need parametric types, see below.
Immutable Structs
Structs defined with struct areImmutableand their fields cannot be modified after creation:
Example
julia
p.
x
=
10
ERROR: setproperty
!
:
immutable
struct of
type
Point cannot be changed
Immutability has many benefits:
- More efficient: the compiler can keep small objects entirely in registers or on the stack, and even skip memory allocation altogether.
- Safer: once an object's value is created, it cannot be accidentally modified.
- Two instances with identical fields are completely equivalent (=== is true).
Example
julia
struct ImmutablePoint
x::
Int
y::
Int
end
julia
ImmutablePoint
(
1
,
2
)
=== ImmutablePoint
(
1
,
2
)
Same value means the same object
true
Best practices:In Julia you should prefer immutable structs; use mutable struct only when you really need to modify an object's state.
Mutable Structs (mutable struct)
Types defined with mutable struct allow an instance's fields to be modified:
Example
julia
mutable struct Stack
items::
Vector
{
Any
}
name::
String
end
julia
s = Stack
(
[
]
,
"RUNOOB Stack"
)
Stack
(
[
]
,
"RUNOOB Stack"
)
julia
push
!
(
s.
items
,
1
)
Modify a field
1
-element
Vector
{
Any
}
:
1
julia
s.
name
=
"Renamed"
"Renamed"
Mutable objects are allocated on the heap and identified by address, so two instances with the same content are still different objects:
Example
julia
a = Stack
(
[
]
,
"x"
)
;
b = Stack
(
[
]
,
"x"
)
;
julia
a === b
Different objects
false
julia
a == b
Compare by field by default? No, by default == is equivalent to ===
false
If you want == to compare by field, you can define your own == method:
Example
julia
Base.:
(
==
)
(
a::Stack, b::Stack
)
= a.
name
== b.
name
&&
a.
items
== b.
items
;
julia
a == b
true
const fields
Since Julia 1.8, individual fields of a mutable struct can be marked const to make them unmodifiable:
Example
julia
mutable struct Baz
a::
Int
const
b::
Float64
b cannot be modified after creation
end
julia
baz = Baz
(
1
,
1.5
)
;
julia
baz.
a
=
2
2
julia
baz.
b
=
2.0
ERROR: setfield
!
:
const
field .
b
of
type
Baz cannot be changed
Abstract Types
Abstract types (abstract type) cannot be instantiated; they are merely nodes in the type hierarchy used to describe a group of related concrete types, similar to the interface concept in other languages:
Example
Declare an abstract type,<: indicates inheritance from a parent type
julia
abstract
type
Shape
end
julia
abstract
type
Polygon
<
: Shape
end
Polygon is a subtype of Shape
Julia's numeric types form a large hierarchy of abstract types:
Number
├─ Complex
└─ Real
├─ AbstractFloat(Float16/32/64、BigFloat)
├─ Integer
│ ├─ Bool
│ ├─ Signed(Int8...Int128、BigInt)
│ └─ Unsigned(UInt8...UInt128)
├─ Rational
└─ Irrational
<: operator can determine subtype relationships, supertype() queries the parent type, and subtypes() lists direct subtypes:
Example
julia
Integer
<
:
Number
true
julia
Int
<
: AbstractFloat
false
julia
supertype
(
Int64
)
Signed
julia
Any
<
:
Any
Any is the root of all types
true
Parametric Types (Generics)
Parametric types are equivalent to generics in other languages; type parameters are declared with curly braces:
Example
Point's two fields have the same type, both determined by the parameter T
julia
struct Point
{
T
}
x::T
y::T
end
julia
Point
(
1
,
2
)
T is automatically inferred as Int64
Point
{
Int64
}
(
1
,
2
)
julia
Point
(
1.0
,
2.0
)
T is automatically inferred as Float64
Point
{
Float64
}
(
1.0
,
2.0
)
Cannot be inferred when the two parameter types differ
julia
Point
(
1
,
2.0
)
ERROR: MethodError: no method matching Point
(
::
Int64
, ::
Float64
)
Type parameters can be constrained to require that they be a subtype of some abstract type:
Example
T must be a subtype of Real
julia
struct RPoint
{
T
<
:
Real
}
x::T
y::T
end
julia
RPoint
(
1
,
2
)
RPoint
{
Int64
}
(
1
,
2
)
julia
RPoint
(
1
,
"a"
)
ERROR: TypeError:
in
RPoint,
in
T, expected T
<
:
Real
, got a value of
type
String
Parametric types are also often used to constrain a field to a certain kind of container:
Example
Wrap a vector
julia
struct Wrapper
{
T
}
data::
Vector
{
T
}
end
julia
Wrapper
(
[
1
,
2
,
3
]
)
Wrapper
{
Int64
}
(
[
1
,
2
,
3
]
)
Union parameters can express the semantics of 'possibly missing', similar to Maybe in other languages
julia
struct MaybeValue
value::
Union
{
Int
, Nothing
}
end
julia
MaybeValue
(
10
)
MaybeValue
(
10
)
julia
MaybeValue
(
nothing
)
MaybeValue
(
nothing
)
Important concept - type invariance:
Vector{Int}EitherVector{Real}a subtype of it! Even if Int <: Real holds. This is because Vector{Real} stores pointers in memory while Vector{Int} stores compact integers, so their memory layouts are completely different. To accept a "vector of any element type", you should writeVector{<:Real}.
Example
julia
Vector
{
Int
}
<
:
Vector
{
Real
}
false
julia
Vector
{
Int
}
<
:
Vector
{
<
:
Real
}
Using <:Real to express "a subtype of Real"
true
Custom Constructors
You can define additional constructor methods to implement argument validation or provide convenient ways of creation.
Outer constructorsDefined outside the struct, they ultimately call the default constructor:
Example
julia
struct Foo
bar
baz
end
Single-argument constructor: both fields take the same value
julia
Foo
(
x
)
= Foo
(
x, x
)
Foo
julia
Foo
(
1
)
Foo
(
1
,
1
)
Inner constructorsDefined inside the struct, they can use the new keyword to create instances and are suitable for argument validation:
Example
julia
struct OrderedPair
x::
Real
y::
Real
Inner constructor: validate x <= y
OrderedPair
(
x, y
)
= x
y
?
error
(
"out of order"
)
: new
(
x, y
)
end
julia
OrderedPair
(
1
,
2
)
OrderedPair
(
1
,
2
)
julia
OrderedPair
(
2
,
1
)
ERROR: out of order
Once an inner constructor is defined, the default constructor is no longer generated; all instances must be created through the validation logic, which guarantees the type's invariants.
Enumeration Type
The @enum macro can quickly define enumeration types:
Example
Define an enum; default values start from 0, or can be specified explicitly
julia
@enum Fruit apple=
1
banana orange
Example
julia
apple
apple::Fruit =
1
julia
orange
orange::Fruit =
3
julia
Fruit
(
2
)
Get an enum member by value
banana::Fruit =
2
julia
Int
(
apple
)
Get the value of an enum member
1
Quick Reference for Type Operations
| Function / Operator | Description |
|---|---|
typeof(x) |
Query the concrete type of value x |
isa(x, T) |
Determine whether x is an instance of type T |
T1 <: T2 |
Determine whether T1 is a subtype of T2 |
supertype(T) |
Query the direct parent type of T |
subtypes(T) |
List the direct subtypes of T |
fieldnames(T) |
Query the tuple of field names of a struct |
fieldtypes(T) |
Query the tuple of field types of a struct |
Union{T1, T2} |
Type union: a value can be of any one of the types |
Union{} |
Empty type (bottom type), with no instances |
Nothing / nothing |
The type representing "no value" / its sole instance |
Example
julia
fieldnames
(
Point
)
(
:x, :y
)
julia
fieldtypes
(
Point
)
(
Int64
,
Int64
)
julia
isa
(
1
,
Int
)
true
julia
isa
(
1
,
Any
)
true
julia
typeof
(
nothing
)
Nothing