Julia Parametric Structs
A parametric struct is a struct whose type name carries one or more type parameters. One struct shape can then serve many field types.
One parameter shapes both fields
Point{Int64} holds two integers. Its printed form shows both values.
struct Point{T}
x::T
y::T
end
p = Point{Int64}(3, 4)
println(p)
println(typeof(p))Two parameters can mix field types
Pair{Int64, String} holds an integer and text. Each field keeps its own type.
struct Pair{A, B}
first::A
second::B
end
p = Pair{Int64, String}(1, "one")
println(p.first)
println(p.second)
println(typeof(p))Different parameters make different types
A Point{Int64} is not a Point{Float64}. The type test shows this plainly.
struct Point{T}
x::T
y::T
end
p = Point{Int64}(1, 2)
println(p isa Point{Int64})
println(p isa Point{Float64})Example
struct Point{T}
x::T
y::T
end
sum_coords(p::Point{T}) where T <: Number = p.x + p.y
println(sum_coords(Point{Int64}(3, 4)))
println(sum_coords(Point{Float64}(1.5, 2.5)))Key points
- Parametric struct: a parametric struct is a struct whose type name carries parameters.
- Point shape: Point{T} has two fields of type T.
- Two parameters: Pair{A, B} can mix two different field types.
- Type name: the parameters become part of the full type name.
- Different parameters: different parameters make different types.
In this example, Point{T} holds two values of one type. A method adds the two fields, it works for an integer point with sum 7 and for a decimal point with sum 4.0.
Note
a field keeps the type its parameter stands for.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is the type of Point{Float64}(1.5, 2.5)?