Julia Interfaces Tutorial
last modified November 18, 2026
In Julia, interfaces are informal contracts that define a set of methods a type must implement to satisfy a particular behavior. Unlike other languages, Julia does not enforce interfaces explicitly. Instead, they are conventions.
Interfaces are crucial for polymorphism, allowing different types to be used interchangeably if they implement the required methods. The examples below were run with Julia 1.13; each defines a small custom type and then uses it through the generic functions that make up the interface.
Iteration Interface
The iteration interface is built around iterate. A type that
reports Base.HasLength() from Base.IteratorSize must
also provide length, and declaring an element type with
Base.eltype lets collect build a concrete array.
struct MyRange
start::Int
stop::Int
end
Base.iterate(r::MyRange, state=r.start) = state > r.stop ? nothing : (state, state + 1)
Base.IteratorSize(::Type{MyRange}) = Base.HasLength()
Base.length(r::MyRange) = max(r.stop - r.start + 1, 0)
Base.eltype(::Type{MyRange}) = Int
println(collect(MyRange(1, 5)))
println(sum(MyRange(1, 5)))
This example defines a custom range type that supports iteration. The two-argument
form of iterate returns the next element and the next state, or
nothing when the range is exhausted. Without the length
method, collect would fail with a MethodError because
we promised a known length; without eltype, the collected array
would have element type Any.
$ julia main.jl [1, 2, 3, 4, 5] 15
Indexing Interface
Indexing is provided by getindex for reading and
setindex! for writing. Together they make the bracket syntax
a[i] and a[i] = v work on a custom type.
struct MyArray
data::Vector{Int}
end
Base.getindex(a::MyArray, i::Int) = a.data[i]
Base.setindex!(a::MyArray, v::Int, i::Int) = a.data[i] = v
a = MyArray([10, 20, 30])
println(a[2])
a[2] = 99
println(a[2])
This example defines a custom array type that supports indexing. The methods
simply forward the operation to the wrapped vector; Julia's bracket syntax is
lowered to calls to getindex and setindex!.
$ julia main.jl 20 99
AbstractArray Interface
An array-like type uses size to report its dimensions and
getindex to read its elements. These are the two core methods that
generic code expects from an array.
struct MyMatrix
data::Matrix{Int}
end
Base.size(m::MyMatrix) = size(m.data)
Base.getindex(m::MyMatrix, i::Int, j::Int) = m.data[i, j]
m = MyMatrix([1 2; 3 4])
println(size(m))
println(m[2, 1])
This example defines a custom matrix type that behaves like an array. The
two-dimensional getindex method accepts a row and a column, and
size returns a tuple of the two dimensions.
$ julia main.jl (2, 2) 3
AbstractFloat Interface
A type that behaves like a floating-point number defines arithmetic operators
such as +, -, and *. Because these
operators live in Base, their method definitions must be qualified
with Base..
struct MyFloat
value::Float64
end
Base.:+(a::MyFloat, b::MyFloat) = MyFloat(a.value + b.value)
Base.:-(a::MyFloat, b::MyFloat) = MyFloat(a.value - b.value)
Base.:*(a::MyFloat, b::MyFloat) = MyFloat(a.value * b.value)
println((MyFloat(1.5) + MyFloat(2.0)).value)
println((MyFloat(1.5) - MyFloat(2.0)).value)
println((MyFloat(1.5) * MyFloat(2.0)).value)
This example defines a custom floating-point-like type with arithmetic
operations. Each method unwraps the value field, performs the
calculation, and wraps the result in a new MyFloat. The colon in
Base.:+ is needed because the operator is written in prefix form
as a function name.
$ julia main.jl 3.5 -0.5 3.0
AbstractString Interface
A string-like type reports how many code units it contains with
ncodeunits and exposes individual bytes with codeunit.
These are the basics that generic string code builds upon.
struct MyString
data::String
end
Base.ncodeunits(s::MyString) = ncodeunits(s.data)
Base.codeunit(s::MyString, i::Int) = codeunit(s.data, i)
s = MyString("hello")
println(ncodeunits(s))
println(codeunit(s, 2))
This example defines a custom string type that behaves like a standard string.
Both methods delegate to the wrapped String; the second argument of
codeunit is a 1-based byte index, and the returned value is a
UInt8, printed here as the number 101 (the letter e).
$ julia main.jl 5 101
AbstractDict Interface
A dictionary-like type provides getindex for lookup with a default
value and haskey to test whether a key is present. The
three-argument get(d, key, default) form avoids an error when a key
is missing.
struct MyDict
data::Dict{String, Int}
end
Base.get(d::MyDict, key::String, default) = get(d.data, key, default)
Base.haskey(d::MyDict, key::String) = haskey(d.data, key)
d = MyDict(Dict("a" => 1))
println(get(d, "a", 0))
println(get(d, "z", 0))
println(haskey(d, "a"))
This example defines a custom dictionary type that supports key-value lookups.
The first get call finds the stored value; the second returns the
default value 0 because the key "z" is not present.
$ julia main.jl 1 0 true
AbstractSet Interface
A set-like type provides in for membership tests and
length for its number of elements. These two methods are enough for
many generic operations that work on sets.
struct MySet
data::Set{Int}
end
Base.in(x::Int, s::MySet) = x in s.data
Base.length(s::MySet) = length(s.data)
s = MySet(Set([1, 2, 3]))
println(2 in s)
println(9 in s)
println(length(s))
This example defines a custom set type that supports membership checks. The
in method delegates to the wrapped Set, so the result
is the same as for a built-in set.
$ julia main.jl true false 3
AbstractChannel Interface
A channel-like type is used for communication between tasks. It provides
put! to send a value and take! to receive one.
struct MyChannel
data::Channel{Int}
end
Base.put!(c::MyChannel, x::Int) = put!(c.data, x)
Base.take!(c::MyChannel) = take!(c.data)
c = MyChannel(Channel{Int}(1))
put!(c, 42)
println(take!(c))
This example defines a custom channel type for inter-task communication. The
buffer size of 1 allows one value to be stored, which take! then
removes and returns.
$ julia main.jl 42
AbstractIO Interface
An I/O-like type provides read to get bytes and write
to store them. Here we wrap an IOBuffer, an in-memory stream.
struct MyIO
data::IOBuffer
end
Base.read(io::MyIO, n::Int) = read(io.data, n)
Base.write(io::MyIO, x::UInt8) = write(io.data, x)
io = MyIO(IOBuffer())
write(io, UInt8(65))
println(String(take!(io.data)))
This example defines a custom I/O type for reading and writing data. We write a
single byte, the ASCII code for A, then read the buffer back and
convert it to a String.
$ julia main.jl A
AbstractTask Interface
A task-like type wraps a Task and forwards schedule
to start it and wait to block until it finishes.
struct MyTask
task::Task
end
Base.schedule(t::MyTask) = schedule(t.task)
Base.wait(t::MyTask) = wait(t.task)
t = MyTask(@task println("the task has finished"))
schedule(t)
wait(t)
This example defines a custom task type for asynchronous execution. The
@task macro creates a task that prints a message, and
wait makes sure the message is printed before the script exits.
Note that wait itself returns nothing; use
fetch when you need a task's result value.
$ julia main.jl the task has finished
Best Practices for Interfaces
These guidelines help when implementing an interface for a custom type.
- Follow Conventions: Adhere to Julia's informal interface conventions.
- Document Behavior: Clearly document expected behavior for custom types.
- Test Thoroughly: Ensure custom types work with generic functions.
- Use Abstract Types: Leverage abstract types for flexible design.
Source
Julia Interfaces documentation
Julia Iteration Interface documentation
In this tutorial, we explored Julia interfaces with practical examples, covering iteration, indexing, arrays, and more. Interfaces enable flexible and reusable code in Julia. Continue with Julia modules to see how custom types are organized, or revisit Julia functions for the generic functions behind these interfaces.
Author
List all Julia tutorials.