Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Classes and Modules

Structs, Records and Value Types

Learn the difference between Crystal classes and structs, how value semantics work, and when to use struct, the record macro, Tuple and NamedTuple for fast, lightweight data.

Classes create reference types: variables hold a pointer to an object living on the heap. Crystal also has value types: data that is copied when you pass it around and usually lives on the stack, so it is cheaper and does not need garbage collection. Structs, tuples and named tuples are the lightweight data carriers of Crystal. This lesson explains how they differ from classes and how to choose.

Crystal listings are read-only on this site. Ruby's Struct and Data are used as runnable stand-ins; they do not have Crystal's stack-allocation or copy-on-pass behaviour, and the lesson shows how to see the copy semantics by hand.

Class versus struct

The syntax is nearly identical; only the keyword changes.

CRYSTAL
struct Point
  getter x : Int32
  getter y : Int32

  def initialize(@x, @y)
  end

  def +(other : Point) : Point
    Point.new(x + other.x, y + other.y)
  end
end

a = Point.new(1, 2)
b = Point.new(10, 20)
puts (a + b).x      # 11
puts (a + b).y      # 22

The behavioural differences are what matter:

class struct
Stored Heap (pointer) Stack or inline (value)
Assignment b = a Both names refer to the same object b is an independent copy
Passed to a method By reference A copy is passed
Mutation visible to caller Yes No (the method changes its copy)
Inheritance Yes A struct may inherit from an abstract struct only, and cannot be inherited from if concrete
nil Can use reference types that may be nil Cannot be nil by itself
Garbage collection Yes No allocation, so none

Because structs are small, copied values, they are the right default for immutable "things with a value": coordinates, colours, money amounts, date ranges.

Copy semantics in action

CRYSTAL
struct Counter
  property n : Int32

  def initialize(@n = 0)
  end
end

def bump(counter : Counter)
  counter.n += 1
  counter.n
end

c = Counter.new
puts bump(c)     # 1  (the method changed its own copy)
puts c.n         # 0  (the original is untouched)

With a class Counter the same code would print 1 and then 1, because both names would refer to one object. Choose a struct when you want that safety, and a class when many parts of the program must share and change one object.

The Ruby stand-in below shows the contrast by copying on purpose. Ruby's Struct is a reference type, so we call dup to get the value behaviour:

Ruby Stand-in: reference versus copy in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The record macro

For plain data you can skip the boilerplate with record, a macro that creates a struct with a constructor and getters:

CRYSTAL
record User, id : Int32, name : String, admin : Bool = false

ada = User.new(1, "Ada", true)
puts ada.name        # Ada
puts ada.admin       # true
puts ada             # User(@id=1, @name="Ada", @admin=true)

record structs are immutable (only getters), print readably and compare by value: User.new(1, "A") == User.new(1, "A") is true. To "change" one, create a copy with ada.copy_with(name: "Ada L.").

Add behaviour by opening a body:

CRYSTAL
record Money, cents : Int64, currency : String do
  def to_s(io : IO) : Nil
    io << currency << " " << cents // 100 << "." << (cents % 100).to_s.rjust(2, '0')
  end
end

puts Money.new(1999, "USD")    # USD 19.99

Tuple

A tuple is a fixed-size, ordered group whose elements may have different types. Its type records every position.

CRYSTAL
pair = {1, "one"}
puts typeof(pair)       # Tuple(Int32, String)
puts pair[0]            # 1
puts pair[1].upcase     # ONE (the compiler knows index 1 is a String)

number, word = pair     # destructuring

An Array(Int32 | String) also holds mixed values, but loses the position-to-type link and allocates on the heap. Tuples are ideal for returning several values from a method.

NamedTuple

A named tuple gives each element a name:

CRYSTAL
point = {x: 3, y: 4}
puts typeof(point)      # NamedTuple(x: Int32, y: Int32)
puts point[:x]          # 3
puts point[:y]          # 4
puts Math.sqrt(point[:x] ** 2 + point[:y] ** 2)   # 5.0

Keys are checked at compile time: point[:z] does not compile. Named tuples are what the **options double splat collects (see methods), and they are a convenient immutable record when you do not want to declare a struct.

Ruby Stand-in: Struct, Data and tuple-like values in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby's Data.define is the closest match for Crystal's record: immutable, compared by value, with a copy-with-changes method.

Choosing the right shape

You need Use
Behaviour, identity, shared mutable state class
A small immutable value with methods struct or record
Return a couple of values from a method Tuple
A quick record with named fields NamedTuple
A collection of the same type Array (see the collections chapter)

A struct larger than a few machine words is copied every time it is passed, so for large data prefer a class. A reasonable guide: structs of up to a handful of fields are fine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you pass a struct to a method that modifies it?

    Structs are value types and are copied when passed.
  2. 2. Which macro creates an immutable data struct with a constructor and getters in one line?

    record User, id : Int32, name : String defines the whole struct.
  3. 3. What is the type of {1, "one"}?

    A tuple records the type of each position.
  4. 4. When is a class a better choice than a struct?

    Classes have identity and are shared by reference, which is what shared mutable state needs.

Summary

  • Classes are reference types on the heap; structs are value types that are copied on assignment and when passed.
  • record creates an immutable struct with value equality in one line; copy_with makes modified copies.
  • Tuple and NamedTuple are typed, fixed-size groups, great for multiple return values and small records.
  • Use structs for small values, classes for identity and shared state.

Next: Modules and Mixins