名前付きタプル

2026年3月22日
1 分

名前付きタプル(named tuple)は、タプルの各要素に名前を付けられるものだ。連想配列のようなものかと思ったけど、辞書(dictionary)というのが別にあるので、ちょっと違うらしい。

とにかく試してみる。

julia> nt = (a = 1, b = 2, c = 3)
(a = 1, b = 2, c = 3)

julia> typeof(nt)
@NamedTuple{a::Int64, b::Int64, c::Int64}

型名の最初についている @ は何だろう?

名前付きタプルの要素には、名前でアクセスできる。

julia> nt.a
1

julia> nt[:b]
2

. でも [ ] でもアクセスできる。:b はシンボルというもののようだ。 また、ふつうのタプルと同じようにインデックスでもアクセスできる。

julia> nt[3]
3

immutable なオブジェクトなので、値の更新や追加はできない。

julia> nt.c = 10
ERROR: setfield!: immutable struct of type NamedTuple cannot be changed
Stacktrace:
 [1] setproperty!(x::@NamedTuple{a::Int64, b::Int64, c::Int64}, f::Symbol, v::Int64)
   @ Base .\Base_compiler.jl:58
 [2] top-level scope
   @ REPL[15]:1

julia> nt[:d] = 4
ERROR: MethodError: no method matching setindex!(::@NamedTuple{a::Int64, b::Int64, c::Int64}, ::Int64, ::Symbol)
The function `setindex!` exists, but no method is defined for this combination of argument types.
Stacktrace:
 [1] top-level scope
   @ REPL[16]:1

keys 関数と values 関数で名前(「キー」と呼ぶ)と値を得られる。

julia> keys(nt)
(:a, :b, :c)

julia> values(nt)
(1, 2, 3)