fieldtype

fieldtype(T, name::Symbol | index::Int)

Determine the declared type of a field (specified by name or index) in a composite DataType T.

Examples

In the Julia programming language, the fieldtype function is used to determine the declared type of a field in a composite DataType T. It takes either the field name as a Symbol or the field index as an Int as arguments.

  1. Get the type of a named field:

    julia> struct Person
              name::String
              age::Int
              height::Float64
          end
    
    julia> fieldtype(Person, :name)
    String

    This example retrieves the type of the name field in the Person struct, which is String.

  2. Get the type of a field using index:

    julia> struct Point
              x::Float64
              y::Float64
              z::Float64
          end
    
    julia> fieldtype(Point, 2)
    Float64

    Here, we obtain the type of the field at index 2 (y) in the Point struct, which is Float64.

  3. Handle edge cases when accessing non-existent fields:

    julia> struct Car
              brand::String
              model::String
          end
    
    julia> fieldtype(Car, :color)
    ERROR: type Car has no field color

    In this example, attempting to access a non-existent field (color) in the Car struct results in an error. Make sure to provide a valid field name or index to avoid such errors.

Common mistake example:

julia> struct Book
           title::String
           author::String
       end

julia> fieldtype(Book, "author")
ERROR: MethodError: no method matching fieldtype(::Type{Book}, ::String)

In this example, the field name is provided as a string ("author") instead of a symbol (:author). It's important to use the correct format for the field name to retrieve the type successfully.

See Also

BigFloat, BigInt, Dict, eltype, fieldtype, Float32, Float64, IntSet, isa, isalnum, isalpha, isascii, iseltype, isequal, isgraph, isimmutable, isinteractive, isleaftype, isnull, ispunct, isspace, issubtype, keytype, Nullable, NullException, promote_type, typeintersect, typejoin, typemax, typemin, typeof, Val, valtype,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: