Classes

Crystal Structs

Defining Structs

Crystal structs are lightweight value types with fields.

Introduction to Crystal Structs

In Crystal, structs provide a way to create lightweight value types. They are similar to classes but are optimized for performance, especially when dealing with simple data structures.

Structs are often used for objects that have a short lifecycle or are frequently created and destroyed, as they do not have the overhead of garbage collection.

Defining a Struct

Structs in Crystal are defined using the struct keyword. You can define fields within the struct, which are the data components that make up the struct.

Creating and Using Structs

Once a struct is defined, you can create instances of it and access its fields directly. Structs do not support inheritance, but they can include modules.

Methods in Structs

Like classes, structs can also have methods. These methods can operate on the fields of the struct, providing functionality specific to the data they hold.

Structs vs Classes

While both structs and classes are used to define objects, there are some key differences:

  • Memory Management: Structs do not require garbage collection, making them more efficient for short-lived objects.
  • Inheritance: Structs do not support inheritance, unlike classes. They can, however, include modules.
  • Usage: Structs are ideal for small data structures and when performance is crucial.
Previous
Classes