Structs

Intermediate Julia

Anthony Markham

Quantitative Developer

Structs - introduction

  • Structs are an application of composite types.
  • These are like other types, but with as many fields as you want
  • We can use a composite type to then create an object, a representation of our type.
Intermediate Julia

Structs - syntax

  • Use the struct keyword to define a structure.
  • Each field within the struct is indented inside the struct declaration.
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(steve.height)
180
Intermediate Julia

Structs - typeof object

  • The type of steve is Person.
struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
println(typeof(steve))
Person
Intermediate Julia

Structs - demonstrate immutability

  • A struct is immutable by default.
# It's Steve's birthday!
steve = Person(18, 180, "London")
steve.age = 19
setfield!: immutable struct of type Person cannot be changed
Intermediate Julia

Structs - mutable structs

  • Use the mutable keyword to create a mutable struct.
mutable struct Person
    age
    height
    location
end
steve = Person(18, 180, "London")
steve.age = 19
println(steve)
Person(19, 180, "London")
Intermediate Julia

Structs - typed structs

  • We can specify a data type for each field in our struct definition.
mutable struct Person
    age::Int64
    height::Int64
    location::String
end
steve = Person(18.5, 180, "London")
InexactError: Int64(18.5)
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...