From e33a26675ac941ad88d66762ce041f6568e32819 Mon Sep 17 00:00:00 2001 From: "Tamas K. Papp" Date: Thu, 11 Oct 2018 16:09:27 +0200 Subject: [PATCH] Add Base.fieldtypes. --- base/exports.jl | 1 + base/reflection.jl | 18 ++++++++++++++++++ doc/src/base/base.md | 1 + test/reflection.jl | 4 ++++ 4 files changed, 24 insertions(+) diff --git a/base/exports.jl b/base/exports.jl index e7cdc8808100b..80b9cb98c626e 100644 --- a/base/exports.jl +++ b/base/exports.jl @@ -694,6 +694,7 @@ export fieldname, fieldnames, fieldcount, + fieldtypes, propertynames, isabstracttype, isbitstype, diff --git a/base/reflection.jl b/base/reflection.jl index 066125fda10a9..a62e1ecd54eab 100644 --- a/base/reflection.jl +++ b/base/reflection.jl @@ -623,6 +623,24 @@ function fieldcount(@nospecialize t) return length(t.types) end +""" + fieldtypes(T::Type) + +The declared types of all fields in a composite DataType `T` as a tuple. + +# Examples +```jldoctest +julia> struct Foo + x::Int64 + y::String + end + +julia> fieldtypes(Foo) +(Int64, String) +``` +""" +fieldtypes(T::Type) = ntuple(i -> fieldtype(T, i), fieldcount(T)) + # return all instances, for types that can be enumerated """ diff --git a/doc/src/base/base.md b/doc/src/base/base.md index 0567e934a5944..53c557583b59d 100644 --- a/doc/src/base/base.md +++ b/doc/src/base/base.md @@ -167,6 +167,7 @@ Base.isconcretetype Base.isbits Base.isbitstype Core.fieldtype +Base.fieldtypes Base.fieldcount Base.fieldoffset Base.datatype_alignment diff --git a/test/reflection.jl b/test/reflection.jl index db85f100af910..2c525ea0fc9f3 100644 --- a/test/reflection.jl +++ b/test/reflection.jl @@ -262,6 +262,10 @@ tlayout = TLayout(5,7,11) @test fieldtype((NamedTuple{(:a,:b),T} where T<:Tuple{Vararg{Integer}}), 2) === Integer @test_throws BoundsError fieldtype(NamedTuple{(:a,:b)}, 3) +@test fieldtypes(NamedTuple{(:a,:b)}) == (Any, Any) +@test fieldtypes((NamedTuple{T,Tuple{Int,String}} where T)) === (Int, String) +@test fieldtypes(TLayout) === (Int8, Int16, Int32) + import Base: datatype_alignment, return_types @test datatype_alignment(UInt16) == 2 @test datatype_alignment(TLayout) == 4