Variables in Crystal
In Crystal, variables are explicitly declared and used by the compiler to check type-correctness of function calls.
# Variables are declared using the `=` operator
a = "initial"
puts a
# You can declare multiple variables at once
b, c = 1, 2
puts "#{b} #{c}"
# Crystal will infer the type of initialized variables
d = true
puts d
# Variables declared without a corresponding
# initialization are given their type's default value.
# For example, the default value for Int32 is 0.
e = 0
puts e
# In Crystal, there's no special syntax for short
# declaration. The `=` operator is used for both
# declaration and assignment.
f = "apple"
puts f
To run the program, save it as variables.cr
and use the crystal
command:
$ crystal variables.cr
initial
1 2
true
0
apple
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.