liveBook · Manning

Element type

As explained in Julia as a Second Language

An element type is the type specification governing the values stored as elements of a collection such as an array.

An element type specifies what kind of values a collection stores. Julia displays it when showing an array, such as `Vector{Float64}` or `Vector{Int8}`. If no type is supplied, Julia infers one from the values. section 4.6

Choose or inspect an array’s element type with familiar constructors and `eltype`:

  • `ones`, `zeros`, and `rand` can receive an element type, as in `ones(Int8, 5)` or `zeros(UInt8, 4)`. section 4.6
  • Prefix an array literal to require a type: `Int8[72, 69, 76, 76, 79]`. section 4.6
  • Call `eltype(xs)` to inspect the element type; typical results include `Int8`, `Int64`, and `Bool`. section 4.6

Homogeneous arrays and mixed data

Arrays are intended for homogeneous data. An integer array rejects a string assignment because Julia cannot convert the string to `Int64`: `xs = [4, 5, 3]`; `xs[1] = "hi"` produces a `MethodError`. A mixed array such as `["hawaiian", 'S', 10.5]` instead has element type `Any`, allowing values of different kinds. section 4.9

Tuples preserve individual types

A pizza record can be represented as `("hawaiian", 'S', 10.5)`, whose type is `Tuple{String, Char, Float64}`. Unlike an `Any` array, the tuple records each position’s type and cannot be modified. section 4.9

How Julia as a Second Language covers it

How deep it goes
Explains typed constructors, literals, inference, inspection, and assignment errors, while deferring fuller type-system details.
Examples
Demonstrates typed numeric arrays, an `Int8` literal, mixed pizza data, failed assignments, and a typed pizza tuple.
What it assumes
Assumes basic array and tuple creation while teaching element-type selection, inference, and mixed-data behavior from concrete examples.
What you can do after
Evaluate and construct collections with deliberate element types, inspect them with `eltype`, and interpret incompatible-assignment errors.
How it connects
Connects element types with arrays, tuples, type inference, the `Any` type, strings, characters, and immutability.

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.