Julia Structs
A struct is a custom type that groups named fields into one value. Each field has a name and a type.
Define a struct and build a value
The fields are listed one per line, each with its type. The built value prints with its type name and fields.
struct Person
name::String
age::Int
end
p = Person("Ana", 31)
println(p)Read fields with a dot
A dot followed by a field name reads that field. The two lines below read the name and the age.
struct Person
name::String
age::Int
end
p = Person("Ana", 31)
println(p.name)
println(p.age)A mutable struct can change
The mutable struct below starts at 0. Its field is then changed to 5.
mutable struct Counter
n::Int
end
c = Counter(0)
c.n = 5
println(c.n)
println(c)Example
struct Person
name::String
age::Int
end
p = Person("Ben", 25)
println(p.name)
println(p.age + 1)
mutable struct Counter
n::Int
end
c = Counter(10)
c.n = c.n + 1
println(c.n)Key points
- struct: the struct keyword starts a type definition, and end closes it.
- Field: one named piece of a struct, written with its type as name::String.
- Build: Person("Ana", 31) creates a value, giving the fields in order.
- Field access: p.name reads the name field of the value p.
- Print: a struct value prints as Person("Ana", 31), showing the type and its fields.
- Immutable: a plain struct value cannot be changed after it is built.
In this example, a Person value is built for Ben, and its name field prints first. Adding 1 to the age field prints 26, while the stored age stays 25. A mutable Counter then has its field raised from 10 to 11, and the new value prints.
Note
a mutable struct is the changeable form, and its fields can be reassigned.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
How do you read the age field of a Person value stored in p?