Julia Tuple Types in Depth
Tuple types are types that describe a fixed list of values, one type per position. Each position keeps its own type.
A tuple type lists one type per position
The type and its field types match position by position. The integer comes first and the string comes second.
println(Tuple{Int, String})
println(fieldtypes(Tuple{Int, String}))One type repeated gives a fixed-length list type
The repeated type fills every position. A value of that type holds three integers.
println(NTuple{3, Int})
v = NTuple{3, Int}((1, 2, 3))
println(v)
println(length(v))
println(sum(v))Destructuring names each part at once
One step splits the value into three named parts. Each part keeps its own value.
t = (7, "seven", true)
a, b, c = t
println(a)
println(b)
println(c)Example
data = (10, "ten", 2.5)
println(fieldtypes(typeof(data)))
println(length(data))
println(data[2])Key points
- Tuple{Int, String}: a type for a pair holding an integer then a string.
- NTuple{3, Int}: a type for three copies of the integer type.
- Position type: the type listed for one numbered position in a tuple type.
- Use fieldtypes to list the position types of a tuple type in order.
- Destructuring: splitting a tuple value into named parts in one step.
In this example, data holds an integer, a string, and a decimal in that order. The field types list those three position types. The length and the second value confirm the order.
Note
a tuple type is fixed in length, so a value with a different length has a different type.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does fieldtypes(Tuple{Int, String}) return?