Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Build system changes
New library functions
---------------------

* Exporting function `fieldindex` to get the index of a struct's field ([#58119]).

New library features
--------------------

Expand Down
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,7 @@ export
fieldoffset,
fieldname,
fieldnames,
fieldindex,
fieldcount,
fieldtypes,
hasfield,
Expand Down
12 changes: 9 additions & 3 deletions base/runtime_internals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1057,7 +1057,7 @@ String
fieldtype

"""
Base.fieldindex(T, name::Symbol, err:Bool=true)
fieldindex(T, name::Symbol, err:Bool=true)

Get the index of a named field, throwing an error if the field does not exist (when err==true)
or returning 0 (when err==false).
Expand All @@ -1069,14 +1069,20 @@ julia> struct Foo
y::String
end

julia> Base.fieldindex(Foo, :z)
julia> fieldindex(Foo, :y)
2

julia> fieldindex(Foo, :z)
ERROR: FieldError: type Foo has no field `z`, available fields: `x`, `y`
Stacktrace:
[...]

julia> Base.fieldindex(Foo, :z, false)
julia> fieldindex(Foo, :z, false)
0
```

!!! compat "Julia 1.13"
This function is exported as of Julia 1.13.
"""
function fieldindex(T::DataType, name::Symbol, err::Bool=true)
return err ? _fieldindex_maythrow(T, name) : _fieldindex_nothrow(T, name)
Expand Down
1 change: 1 addition & 0 deletions doc/src/base/base.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ Base.isstructtype
Base.nameof(::DataType)
Base.fieldnames
Base.fieldname
Base.fieldindex
Core.fieldtype
Base.fieldtypes
Base.fieldcount
Expand Down
4 changes: 4 additions & 0 deletions test/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,10 @@ tlayout = TLayout(5,7,11)
@test fieldtype(Union{Tuple{Char},Tuple{Char,Char}},2) === Char
@test_throws BoundsError fieldtype(Union{Tuple{Char},Tuple{Char,Char}},3)

@test [fieldindex(TLayout, i) for i = (:x, :y, :z)] == [1, 2, 3]
@test fieldname(TLayout, fieldindex(TLayout, :z)) === :z
@test fieldindex(TLayout, fieldname(TLayout, 3)) === 3

@test fieldnames(NTuple{3, Int}) == ntuple(i -> fieldname(NTuple{3, Int}, i), 3) == (1, 2, 3)
@test_throws ArgumentError fieldnames(Union{})
@test_throws BoundsError fieldname(NTuple{3, Int}, 0)
Expand Down
Loading