Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add hasfield to check for field existence #27582

Closed
wants to merge 3 commits into from
Closed
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 @@ -1269,6 +1269,8 @@ Deprecated or removed

* `atan2` is now a 2-argument method of `atan` ([#27248]).

* `hasfield` was added to check if a composite type has a field of a given name ([#27582])

Command-line option changes
---------------------------

Expand Down
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,7 @@ export
fieldname,
fieldnames,
fieldcount,
hasfield,
propertynames,
isabstracttype,
isbitstype,
Expand Down
21 changes: 21 additions & 0 deletions base/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,27 @@ function fieldindex(T::DataType, name::Symbol, err::Bool=true)
return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, err)+1)
end

"""
hasfield(T, name::Symbol)

Return `true` if a composite DataType `T` has a field called `name`.

# Examples
```jldoctest
julia> struct Foo
x::Int64
y::String
end

julia> Base.hasfield(Foo, :x)
true

julia> Base.hasfield(Foo, :balloon)
false
```
"""
hasfield(T::DataType, name::Symbol) = fieldindex(T, name, false) > 0

argument_datatype(@nospecialize t) = ccall(:jl_argument_datatype, Any, (Any,), t)
function argument_mt(@nospecialize t)
dt = argument_datatype(t)
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 @@ -154,6 +154,7 @@ Base.isbitstype
Core.fieldtype
Base.fieldcount
Base.fieldoffset
Base.hasfield
Base.datatype_alignment
Base.datatype_haspadding
Base.datatype_pointerfree
Expand Down
5 changes: 5 additions & 0 deletions test/reflection.jl
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,11 @@ tlayout = TLayout(5,7,11)
@test_throws ArgumentError fieldname(TLayout, 4)
@test_throws BoundsError fieldoffset(TLayout, 4)

for name in (:x, :y, :z)
@test hasfield(TLayout, name)
end
@test !hasfield(TLayout, :parameters)

@test fieldtype(Tuple{Vararg{Int8}}, 1) === Int8
@test fieldtype(Tuple{Vararg{Int8}}, 10) === Int8
@test_throws BoundsError fieldtype(Tuple{Vararg{Int8}}, 0)
Expand Down