Basics

Crystal Variables

Declaring Crystal Variables

Crystal variables use dynamic typing with optional type annotations.

Introduction to Variables in Crystal

In Crystal, variables are used to store data that can be manipulated throughout your program. Variables in Crystal are dynamically typed, meaning the type of the variable is determined at runtime. However, you can optionally specify the type of a variable for clarity and error prevention.

Declaring Variables

To declare a variable in Crystal, you simply assign a value to it using the = operator. You do not need to explicitly specify the type, as Crystal will infer it from the value assigned.

Optional Type Annotations

While Crystal is dynamically typed, you can provide explicit type annotations to variables. This is useful for documentation purposes and can help catch type-related errors during compilation.

Reassigning Variables

Variables in Crystal can be reassigned to new values, as long as the new value is compatible with the variable's type. If a type annotation is provided, only values of that type can be assigned to the variable.

Using Nil in Variables

Crystal variables can also be assigned nil if they are declared with a type that includes Nil. This is useful for representing the absence of a value.

Constants in Crystal

In addition to variables, Crystal also supports constants, which are used to store immutable values. Constants are declared using uppercase letters and must have an explicit type.

Conclusion

Understanding how to declare and use variables is fundamental to programming in Crystal. The ability to use optional type annotations provides flexibility and helps ensure type safety in your code. As you continue learning, you'll find that Crystal's approach to variables combines the best of both dynamic and static typing.

Previous
Syntax