Variables in Erlang

In Erlang, variables are declared implicitly when they are first used. Unlike Go, Erlang uses single assignment, meaning once a variable is bound to a value, it cannot be changed.

-module(variables).
-export([main/0]).

main() ->
    % In Erlang, variables start with an uppercase letter
    A = "initial",
    io:format("~p~n", [A]),

    % You can declare multiple variables at once
    {B, C} = {1, 2},
    io:format("~p ~p~n", [B, C]),

    % Erlang is dynamically typed, so type inference is automatic
    D = true,
    io:format("~p~n", [D]),

    % Variables in Erlang don't have a "zero value". They must be initialized.
    % If you need a default value, you must explicitly assign it.
    E = 0,
    io:format("~p~n", [E]),

    % In Erlang, all variable assignments are done with '='
    F = "apple",
    io:format("~p~n", [F]).

To run this Erlang program:

$ erlc variables.erl
$ erl -noshell -s variables main -s init stop
initial
1 2
true
0
"apple"

In Erlang:

  • Variables must start with an uppercase letter.
  • There’s no need for explicit type declarations.
  • Variables are immutable - once assigned, they can’t be changed.
  • Pattern matching is used for assignment and destructuring.
  • The io:format/2 function is used for output, similar to fmt.Println in Go.
  • There’s no direct equivalent to Go’s := syntax, as all assignments use =.

Erlang’s approach to variables is quite different from Go’s, reflecting its functional programming paradigm and emphasis on immutability.