Get nominal type of field of composite type?


#1

How would one determine the nominal type of a field in a composite type?

For example, suppose I have something like this:

mutable struct MyType
  sub::Number
end

function foo(x::Any)

  # I can get the type of whatever is stored in "sub" like so:
  typeof(x.sub) # For our example, this returns Float64, not Number

  # But suppose I want to know what 'sub' is allowed to be, 
  # like is it always a Float64? Or a Number? Or an Any?

end

x = MyType(2.7);
foo(x) # I'd like this to return Number, not Float64.

More generally, how do I explore the type MyType?

(While we’re here, is there some way to declare that the input “x” must have a field called “sub” without specifying any particular abstract type?)

This if for a some flexible conversion utilities where performance is totally unimportant.


#2

More generally, how do I explore the type MyType?

dump(MyType)

How would one determine the nominal type of a field in a composite type?

julia> Any[ fieldtype(MyType, i) for i in 1:nfields(MyType) ]
1-element Array{Any,1}:
Number

While we’re here, is there some way to declare that the input “x” must have a field called “sub” without specifying any particular abstract type?

Yes: write tests. :slight_smile:


#3

Thanks, @jameson! fieldtype (“Determine the declared type of a field (specified by name or index) in a composite DataType…”) is exactly what I was looking for.

(And for the bonus question: I guess I can use an assert to write a message like, “Hey, input ‘x’ is supposed to have a field called ‘sub’,” but I didn’t know if there was some better way to handle this.)