Crystal Notes: Variables
Published: 2021-07-28
Intro
Like most languages, variables in Crystal are defined with the = operator.
crystal
# Create a string variable
stuff = "stuff"
# Deduce the type of a variable.
typeof(stuff) # => String
# Explicitly define the type of a variable.
stuff : String
# Assign "stuff" value to the stuff variable
stuff = "stuff"
# Define a variable type and assign a value
stuff : String = "stuff"
# Define a constant
THINGS = "thingsConsiderations
- Variable types are inferred by the compiler and do not have to be specifically defined.
- When a variable type is declared, it must be assigned a value before it can be accessed.
- There are no global variables in Crystal, all variables are locally scoped
- A variables value can be reassigned.
- If a constants value is reassigned, the compiler will complain, but the program will still run.
- Variables are defined in snake_case by convention.
- Constants are defined in SHOUTING_SNAKE_CASE by convention.
Links
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/conventions/coding_style.html