logo

How to Check the Element Type Inside a Julia Container 📂Julia

How to Check the Element Type Inside a Julia Container

Overview

To achieve this, use the eltype() function. It likely gets its name from element type.

Code

julia> set_primes = Set([2,3,5,7,11,13])
Set{Int64} with 6 elements:
  5
  13
  7
  2
  11
  3

julia> arr_primes = Array([2,3,5,7,11,13])
6-element Vector{Int64}:
  2
  3
  5
  7
 11
 13

Consider two types of containers that hold prime numbers up to $13$. Honestly, they contain the same data, but one is a set while the other is an array.

julia> typeof(set_primes)
Set{Int64}

julia> eltype(set_primes)
Int64

julia> typeof(arr_primes)
Vector{Int64} (alias for Array{Int64, 1})

julia> eltype(arr_primes)
Int64

Applying typeof() to these distinguishes whether one is a set or an array, whereas eltype() returns the type of elements inside the container, regardless of what the container itself is.

julia> typeof(1:10)
UnitRange{Int64}

julia> eltype(1:10)
Int64

julia> typeof(1:2:10)
StepRange{Int64, Int64}

julia> eltype(1:2:10)
Int64

The difference between 1:10 and 1:2:10, as seen above, demonstrates how eltype() can be usefully applied in the world of Julia programming, which may seem excessively obsessed with types.

Environment

  • OS: Windows
  • julia: v1.6.3