Variables in Crystal
In Crystal, variables are explicitly declared and used by the compiler to check type-correctness of function calls.
To run the program, save it as variables.cr
and use the crystal
command:
Let’s break down the key points:
In Crystal, you don’t need to explicitly declare variable types. The type is inferred from the assigned value.
Multiple variable assignment is supported, as shown with
b, c = 1, 2
.Crystal doesn’t have a separate keyword for variable declaration. The
=
operator is used for both declaration and assignment.Variables are automatically initialized with a default value if not explicitly assigned. For integers, this is 0.
Crystal doesn’t have a special short declaration syntax like
:=
. The=
operator is used consistently.String interpolation is done using
#{...}
within string literals.
Crystal’s syntax is designed to be clean and expressive, making it easy to declare and work with variables in your programs.