Skip to content

Commit 598dd41

Browse files
committed
Support vectors as indices to NamedTuple
Fix #32662, #27021
1 parent 2182389 commit 598dd41

File tree

2 files changed

+6
-0
lines changed

2 files changed

+6
-0
lines changed

base/namedtuple.jl

+2
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ firstindex(t::NamedTuple) = 1
103103
lastindex(t::NamedTuple) = nfields(t)
104104
getindex(t::NamedTuple, i::Int) = getfield(t, i)
105105
getindex(t::NamedTuple, i::Symbol) = getfield(t, i)
106+
getindex(t::NamedTuple, v::AbstractVector{<:Integer}) = (; map(i->keys(t)[i] => t[i], v)...)
107+
getindex(t::NamedTuple, v::AbstractVector{Symbol}) = (; map(i->i => t[i], v)...)
106108
indexed_iterate(t::NamedTuple, i::Int, state=1) = (getfield(t, i), i+1)
107109
isempty(::NamedTuple{()}) = true
108110
isempty(::NamedTuple) = false

test/namedtuple.jl

+4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
@test (a=3,)[:a] == 3
2222
@test (x=4, y=5, z=6).y == 5
2323
@test (x=4, y=5, z=6).z == 6
24+
@test (x=4, y=5, z=6)[1:1] == (x=4,)
25+
@test (x=4, y=5, z=6)[1:2] == (x=4, y=5)
26+
@test (x=4, y=5, z=6)[[1,3]] == (x=4, z=6)
27+
@test (x=4, y=5, z=6)[[:x,:y]] == (x=4, y=5)
2428
@test_throws ErrorException (x=4, y=5, z=6).a
2529
@test_throws BoundsError (a=2,)[0]
2630
@test_throws BoundsError (a=2,)[2]

0 commit comments

Comments
 (0)