Julia Type Parameters in Depth
Type parameters are placeholders inside a type name that stand for other types. One shape can then hold different kinds of values.
One shape can hold an integer
Box{Int64} holds an integer. Its printed form shows the parameter.
struct Box{T}
x::T
end
b = Box{Int64}(5)
println(b)
println(typeof(b))The same shape can hold text
Box{String} holds text. The shape is the same, and the type is different.
struct Box{T}
x::T
end
b = Box{String}("hi")
println(b)
println(typeof(b))The field type follows the parameter
A Box{String} field holds text. Its type is String.
struct Box{T}
x::T
end
b = Box{String}("hello")
println(b.x)
println(typeof(b.x))Example
struct Bag{T}
first::T
second::T
end
bag = Bag{Int64}(3, 4)
println(bag.first + bag.second)
println(typeof(bag))Key points
- Type parameter: a type parameter is a placeholder inside a type name.
- Box shape: Box{T} is one shape with a placeholder named T.
- Field rule: the field type follows the placeholder in the same struct.
- Different types: Box{Int64} and Box{String} are different types.
- No limit: a type parameter with no limit accepts any type.
In this example, Bag{T} has two fields of the same placeholder type. A Bag{Int64} is made with 3 and 4, their sum is 7, and the bag type is Bag{Int64}.
Note
the parameter appears inside the braces after the type name.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What is the type of Box{Int64}(5)?