Learn Julia · 7/15

Custom Types & Structs

6 min read

🧱 Custom Types & Structs in Julia

Welcome! In this guide, we'll explore how to create your own custom data types in Julia using structs. This is a powerful feature that allows you to organize your data in a way that makes sense for your specific problem.

The Problem: Disorganized Data 😵

Imagine you're building a system to track information about users. You might start by storing each piece of information in separate variables:

julia
username = "coder_guy"
email = "[email protected]"
age = 28
is_active = true

This works for one user, but what about a hundred? Or a thousand? You'd have a confusing mess of variables. How can we group related data together in a clean, organized way?

The Solution: Custom Types with struct 💡

Julia allows you to define your own custom data types using the struct keyword. Think of a struct as a blueprint for creating a new type of "thing" in your program. This "thing" can have multiple named fields, each with its own type.

By creating a User struct, we can bundle all the user-related information into a single, cohesive unit.


1. Understanding the Type Hierarchy (Any, Real, Int)

Before we start building our own types, it's helpful to understand how types are organized in Julia.

Definition: Julia has a type hierarchy, which is like a family tree for all its types. At the very top of this tree is the Any type. Every other type in Julia is a descendant of Any.

Think of it like this:

  • Any: The great-great-grandparent of all types. It's an abstract type, meaning you can't create a direct instance of it, but it serves as a way to group related types.
  • Number: A child of Any. It's also an abstract type that represents all kinds of numbers.
  • Real: A child of Number, representing real numbers (not complex).
  • Integer: A child of Real, for whole numbers.
  • Int64: A child of Integer. This is a concrete type, which means you can actually create instances of it (like the number 42). In Julia, you can only create instances of concrete types.

You can explore this hierarchy yourself using the subtypes() and supertype() functions:

julia
subtypes(Number)
# Output: 2-element Vector{Any}:
#  Complex
#  Real

supertype(Int64)
# Output: Signed

Why does this matter? This hierarchy is fundamental to how Julia works, especially with a feature called multiple dispatch, where a function can have different behaviors depending on the types of its arguments.


2. Defining Custom Structs (Composite Types)

Now, let's create our own custom type! We'll use the struct keyword to define a composite type.

Definition: A composite type is a type that is composed of a collection of named fields.

Let's create a struct to represent a point in a 2D space:

julia
struct Point
    x::Float64
    y::Float64
end

Here, we've defined a new type called Point with two fields: x and y, both of which are of type Float64.

Now we can create instances of our new Point type:

julia
p1 = Point(1.5, 2.5)
# Output: Point(1.5, 2.5)

p2 = Point(0.0, -5.0)
# Output: Point(0.0, -5.0)

We can access the fields of a Point instance using dot notation:

julia
p1.x
# Output: 1.5

p2.y
# Output: -5.0

Funny exaggeration: Creating a struct is like inventing a new species of Pokémon. You define its characteristics (fields), and then you can create as many instances of it as you want to roam around in your code! 🐾


3. Mutable vs. Immutable Structs

By default, the structs we've created are immutable.

Definition: An immutable object cannot be changed after it's created. If you want to change a value, you have to create a new object.

If we try to change a field of our immutable Point struct, we'll get an error:

julia
p1 = Point(1.5, 2.5)
p1.x = 3.0  # This will cause an error!
# ERROR: setfield!: immutable struct of type Point cannot be changed

To create a mutable struct, we use the mutable struct keywords:

julia
mutable struct MutablePoint
    x::Float64
    y::Float64
end

Now, we can change the fields of a MutablePoint instance:

julia
mp1 = MutablePoint(1.5, 2.5)
mp1.x = 3.0
mp1
# Output: MutablePoint(3.0, 2.5)

When to use each?

  • Immutable struct:

    • Pros: Generally more efficient and can lead to better performance because the compiler can make more assumptions about them. They are often allocated on the stack, which is faster.
    • Cons: You have to create a new instance every time you want to "change" a value.
  • Mutable struct:

    • Pros: You can modify the fields in place, which can be more convenient.
    • Cons: Can be slightly less performant as they are typically allocated on the heap.

Industry Practice: In high-performance Julia code, the default is to use immutable structs whenever possible. You should only use mutable struct when you have a clear reason to modify the fields of an object after it has been created.

Interesting Fact: The concept of immutability is a cornerstone of functional programming languages and can help in writing code that is easier to reason about and less prone to bugs, especially in parallel and concurrent applications.


4. Constructors: Inner and Outer Methods

Definition: A constructor is a special function that creates an instance of a type. Julia automatically provides a default constructor for your structs that takes all the fields as arguments.

However, sometimes you want more control over how your objects are created. For this, we can define our own constructors. There are two types: inner and outer constructors.

Outer Constructors

An outer constructor is defined outside of the struct definition. It's just like a regular function that happens to create an instance of your struct.

Let's create an outer constructor for our Point struct that allows creating a point at the origin without any arguments:

julia
struct Point
    x::Float64
    y::Float64
end

# Outer constructor
Point() = Point(0.0, 0.0)

origin = Point()
# Output: Point(0.0, 0.0)

Outer constructors are great for providing convenience methods for creating objects.

Inner Constructors

An inner constructor is defined inside the struct block. You use inner constructors to enforce invariants or when the creation of the object is more complex.

When you define an inner constructor, the default constructor is no longer available.

Let's imagine we're creating a RightTriangle struct and we want to ensure that the side lengths are always positive.

julia
struct RightTriangle
    a::Float64
    b::Float64
    c::Float64

    # Inner constructor
    function RightTriangle(a, b)
        if a <= 0 || b <= 0
            error("Side lengths must be positive")
        end
        c = sqrt(a^2 + b^2)
        new(a, b, c)
    end
end

Here's what's happening:

  • The function RightTriangle(a, b) line defines our inner constructor. It only takes a and b as arguments.
  • We check if a and b are positive.
  • We calculate the hypotenuse c.
  • The new(a, b, c) function is a special function only available inside inner constructors that creates a new instance of the struct.

Now, we can only create a RightTriangle by providing two positive side lengths:

julia
triangle = RightTriangle(3.0, 4.0)
# Output: RightTriangle(3.0, 4.0, 5.0)

invalid_triangle = RightTriangle(-1.0, 4.0)
# ERROR: Side lengths must be positive

Industry Standard: It's good practice to provide as few inner constructors as possible, mainly for enforcing essential error checking and transformations. Additional convenience methods should be implemented as outer constructors that call the inner constructors.


📚 Further Reading

Challenge

You are tasked with building a simple system to model financial accounts and transactions in Julia. This will require creating two custom types with specific behaviors for immutability, mutability, and data validation.

  1. Define an immutable Transaction struct.

    • It must have the following fields: id::Int, amount::Float64, currency::String, timestamp::Int, and description::String.
    • Implement an inner constructor that enforces the following data invariants:
      • The amount must be non-negative (>= 0).
      • The currency string must be exactly 3 characters long and all uppercase.
      • If either of these conditions is not met, the constructor should throw an ArgumentError with a descriptive message.
  2. Define a mutable Account struct.

    • It must contain the fields: account_number::String, owner_name::String, balance::Float64, and history::Vector{Transaction}.
  3. Create an outer constructor for Account.

    • This constructor should accept only the account_number and owner_name as arguments.
    • It should initialize the account with a balance of 0.0 and an empty Vector{Transaction} for the history.
  4. Implement the process_transaction! function.

    • The function signature should be process_transaction!(acc::Account, trans::Transaction).
    • This function must modify the Account instance acc by:
      • Adding the trans.amount to the acc.balance.
      • Appending the trans object to the end of the acc.history vector.

Expected result

Your final code should contain the complete definitions for:

  1. An immutable struct named Transaction with the specified fields and an inner constructor that validates input and throws an ArgumentError for invalid data (negative amount or malformed currency).
  2. A mutable struct named Account with the specified fields.
  3. An outer constructor for Account that takes two arguments (account_number, owner_name) and correctly initializes a new account with a zero balance and an empty history.
  4. A function process_transaction! that correctly modifies an Account instance by updating its balance and history based on a given Transaction.
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.