Elixir - Variables
A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
Types of Variables
Elixir supports the following basic types of variables.
These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory.
Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used.
They can take up 2 values which is either true or false.
Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings.
These are functions that can be defined and assigned to a variable, which can then be used to call this function.
There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters.
A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following −
life = 42
This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e.,
life = "Hello world"
Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional '?' OR '!'.
Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something.
In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable −
life = 42
And enter 'life' in your shell, you'll get the output as −
But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function −Live Demo
life = 42 IO.puts life
life = 42 IO.puts(life)
This will give you the following output −