Basic Types and Operations
In this chapter we will learn about Elixir basic types: integers, floats, booleans, atoms, and strings. Let’s see some examples.
Here’s an integer:
42
A float (a floating point number):
3.14159
A boolean value:
true
An atom (a constant whose name is its value):
:elixir
And a string:
"Hello, Elixir!"
We’ll learn more about these types in a moment. Now, let’s see how we can assign them to variables.
Variables and Immutability
Similarly to many other languages, you can assign a value to a variable using = sign.
x = "value"
x
Variables must start with a lowercase letter or an underscore. By convention, the variable names are written in snake_case. Leading underscore has a special meaning, but we’ll learn that (and more details about variables) in the chapter about pattern matching.
You may re-assign the variable name to a different value, even of a different type:
y = "foo"
y = 1
y
However, all data in Elixir is immutable. It means that under the hood, the y from the line 1 and y from the line 2 are two different variables - they just share the same name. We’ll learn more about consequences of this in further chapters.
Variables can be assigned from other variables:
x = "value"
y = x
y
Re-assigning a variable doesn’t affect other variables that were assigned its previous value:
x = "value"
y = x
x = 1
IO.inspect(x)
y
Modules and functions
In Elixir, functions are grouped in modules. To call a function, we use Module.function(comma, separated, arguments). We already called inspect function from the IO module:
IO.inspect("hello")
The Elixir standard library contains many modules and functions. For example, String.duplicate returns a string repeated given number of times:
String.duplicate("hello", 3)
Functions from the Kernel module can be called just by their name, for example:
Kernel.round(1.7)
is the same as:
round(1.7)
In the documentation and guides like this, the convention is to refer to functions using Module.function/arity or function/arity syntax, where ‘arity’ is the number of arguments, for example: IO.inspect/1, String.duplicate/2 or round/1. You can look up the documentation for each function on hexdocs.pm.
Now, let’s learn more about the basic types and how to use them.