Data Types and Variables

From Elixir Wiki
Jump to navigation Jump to search

Data Types and Variables[edit]

Data Types[edit]

Elixir is a dynamically-typed programming language, which means variables can hold different types of data at runtime. Elixir provides a rich set of built-in data types for different purposes. Some of the commonly used data types in Elixir include:

Numeric Types[edit]

Boolean Type[edit]

Atom Type[edit]

String Type[edit]

List Type[edit]

Tuple Type[edit]

Map Type[edit]

Function Type[edit]

Struct Type[edit]

Bit String Type[edit]

PID (Process Identifier) Type[edit]

Variables[edit]

In Elixir, variables are dynamically bound to values, allowing them to be reassigned and hold different types of data. Variable names in Elixir must start with a lowercase letter or an underscore (_). They can contain lowercase letters, uppercase letters, numbers, and underscores. Here's an example of variable assignment:

```elixir x = 42 ```

Variables can also be pattern-matched to extract values from other data structures, such as tuples and maps, or to assign multiple variables simultaneously:

```elixir {a, b} = {1, 2} ```

Multiple assignments can also be done using the pin operator (^) to keep a variable's current value:

```elixir x = 1 ^x = 2 ```

When a variable is redefined within a more nested scope, it creates a new binding that shadows the outer binding:

```elixir x = 1

if true do

 x = 2

end

IO.puts(x) ```

Constants[edit]

Constants in Elixir are defined using the `defconst` macro or `@` module attribute. They are typically used to hold values that should not be changed throughout the program execution:

```elixir defmodule Math do

 @pi 3.1415
 defcalculation(radius) do
   @pi * radius * radius
 end

end ```

In the example above, `@pi` is a constant that can be accessed within the module.

Type Inference[edit]

Elixir employs type inference, which means that the compiler can automatically determine the data type of a variable based on its usage:

```elixir x = 42 ```

In the above code, the compiler infers that `x` is an integer based on the assigned value.

Elixir also provides type specifications using the `@type` module attribute, allowing developers to give explicit type information for better code documentation and tooling support:

```elixir @type name :: String.t ```

Conclusion[edit]

Understanding data types and variables is crucial for writing efficient and reliable Elixir programs. Elixir's flexibility in handling different data types and its support for variables make it a powerful language for various applications.

Template:Languages Template:Software development Template:Programming languages