liveBook · Manning

Nothing

As explained in Julia as a Second Language

The nothing object is the sole runtime value that is an instance of Julia's Nothing type.

What should a search return when it finds no match? In Julia, `findfirst` returns a location when it succeeds and `nothing` when it fails. `nothing` is the value used by convention when something does not exist; it is the sole value of type `Nothing`. section 10.1

julia> findfirst("four", "one two three four")
15:18

julia> findfirst("four", "one two three")

julia> typeof(ans)
Nothing

julia> findfirst("four", "one two three") == nothing
true

Compare a successful `findfirst` result with a failed search, then check the failed result’s type and value. section 10.1

`Nothing` is a composite type with no fields, and `nothing` is defined as `Nothing()`. Constructing `Nothing()` again gives the same object. Another zero-field type can have its own sole object, distinct from `nothing`. section 10.1

Listing 10.1 Nothing type and nothing constant as defined by Julia
struct Nothing
   # look, no fields
end

const nothing = Nothing()

See the short type definition behind `Nothing` and its `nothing` constant. section 10.1

Choose the value that matches the problem:

  • Use `nothing` for absence, such as a failed search or a linked-list terminator. section 10.7
  • Use `missing` for data that exists but is unavailable, such as a missing survey answer. section 10.6 section 10.7
  • Treat `NaN` as a sign of an illegal mathematical operation and an undefined value as uninitialized data. section 10.6

When a field may hold either a string or no value, declare it as `Union{Nothing, String}`. `nothing` can also be the value of an expression: a `while` loop evaluates to it, even though the REPL displays no result for that value. section 10.7 section 3.3

How Julia as a Second Language covers it

How deep it goes
Defines Nothing as a zero-field composite type and demonstrates constructor equality, without developing further type-system internals.
Examples
Shows findfirst returning a location or nothing, repeated Nothing() comparisons, and a while expression with no visible REPL result.
What it assumes
Assumes basic familiarity with REPL expressions and functions while introducing the zero-field type definition directly.
What you can do after
Practice/perform absent-value handling with nothing and declare an optional string field using Union{Nothing, String}.
How it connects
Connects Nothing to type unions, Missing, NaN, undefined values, and control-flow expressions.

Related concepts

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.