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:
username = "coder_guy"
email = "[email protected]"
age = 28
is_active = trueThis 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 ofAny. It's also an abstract type that represents all kinds of numbers.Real: A child ofNumber, representing real numbers (not complex).Integer: A child ofReal, for whole numbers.Int64: A child ofInteger. This is a concrete type, which means you can actually create instances of it (like the number42). In Julia, you can only create instances of concrete types.
You can explore this hierarchy yourself using the subtypes() and supertype() functions:
subtypes(Number)
# Output: 2-element Vector{Any}:
# Complex
# Real
supertype(Int64)
# Output: SignedWhy 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:
struct Point
x::Float64
y::Float64
endHere, 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:
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:
p1.x
# Output: 1.5
p2.y
# Output: -5.0Funny 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:
p1 = Point(1.5, 2.5)
p1.x = 3.0 # This will cause an error!
# ERROR: setfield!: immutable struct of type Point cannot be changedTo create a mutable struct, we use the mutable struct keywords:
mutable struct MutablePoint
x::Float64
y::Float64
endNow, we can change the fields of a MutablePoint instance:
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:
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.
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
endHere's what's happening:
- The
function RightTriangle(a, b)line defines our inner constructor. It only takesaandbas arguments. - We check if
aandbare 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:
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 positiveIndustry 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
- Official Julia Documentation:
- Community Resources:
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.
Define an immutable
Transactionstruct.- It must have the following fields:
id::Int,amount::Float64,currency::String,timestamp::Int, anddescription::String. - Implement an inner constructor that enforces the following data invariants:
- The
amountmust be non-negative (>= 0). - The
currencystring must be exactly 3 characters long and all uppercase. - If either of these conditions is not met, the constructor should throw an
ArgumentErrorwith a descriptive message.
- The
- It must have the following fields:
Define a mutable
Accountstruct.- It must contain the fields:
account_number::String,owner_name::String,balance::Float64, andhistory::Vector{Transaction}.
- It must contain the fields:
Create an outer constructor for
Account.- This constructor should accept only the
account_numberandowner_nameas arguments. - It should initialize the account with a
balanceof0.0and an emptyVector{Transaction}for thehistory.
- This constructor should accept only the
Implement the
process_transaction!function.- The function signature should be
process_transaction!(acc::Account, trans::Transaction). - This function must modify the
Accountinstanceaccby:- Adding the
trans.amountto theacc.balance. - Appending the
transobject to the end of theacc.historyvector.
- Adding the
- The function signature should be
Expected result
Your final code should contain the complete definitions for:
- An immutable
structnamedTransactionwith the specified fields and an inner constructor that validates input and throws anArgumentErrorfor invalid data (negativeamountor malformedcurrency). - A
mutable structnamedAccountwith the specified fields. - An outer constructor for
Accountthat takes two arguments (account_number,owner_name) and correctly initializes a new account with a zero balance and an empty history. - A function
process_transaction!that correctly modifies anAccountinstance by updating itsbalanceandhistorybased on a givenTransaction.