Variables in Elixir

In Elixir, variables are implicitly declared and used. The language uses dynamic typing, which means the type of a variable is determined at runtime.

defmodule Variables do
  def main do
    # Declares and initializes a variable
    a = "initial"
    IO.puts(a)

    # You can declare multiple variables at once
    b = 1
    c = 2
    IO.puts("#{b} #{c}")

    # Elixir will infer the type of initialized variables
    d = true
    IO.puts(d)

    # Variables declared without a corresponding
    # initialization are nil in Elixir
    e = nil
    IO.puts(e)

    # In Elixir, all variables are reassignable by default
    f = "apple"
    IO.puts(f)
  end
end

Variables.main()

To run the program, save it as variables.exs and use the elixir command:

$ elixir variables.exs
initial
1 2
true

apple

In Elixir:

  • Variables are declared and initialized using the = operator.
  • There’s no need for explicit type declarations.
  • Variables are dynamically typed.
  • Uninitialized variables are nil by default.
  • All variables are reassignable unless made immutable using ^ (pin operator).
  • There’s no direct equivalent to Go’s := syntax as Elixir doesn’t require explicit variable declarations.

Elixir’s approach to variables is more flexible than statically typed languages, allowing for quick prototyping and dynamic behavior. However, this flexibility comes with the trade-off of fewer compile-time type checks.