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 1 commit
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
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