Crystal Medium · Lesson 1 · On the house

Structs and value semantics

Know when a struct beats a class: structs copy on assignment and argument passing, compare by fields, and live on the stack. Lesson 1 is free — on the house.

Lessons · Crystal Medium · Lesson 1 of 10 · On the house

Structs and value semantics

Know when a struct beats a class: structs copy on assignment and argument passing, compare by fields, and live on the stack.

Illustration for Crystal
Lesson 1 is on the house.

struct Point looks like a class but is a value type. Assigning it (b = a) or passing it to a method copies every field, so changing the copy never touches the original.

A class is a reference type. cb = ca copies only the reference, so both names point at one object and a change through either is visible through both.

Structs get field-by-field == for free: two Point.new(1, 2) values are equal. Classes compare by identity unless you define ==, so two separate objects with the same fields are not equal.

The trap: pts[0].x = 5 changes a temporary copy returned by [], and the array keeps the old value. Read the element into a variable, change it, and write it back with pts[0] = p.

Methods that return a new struct (def +(o : Point) : Point) are the natural style. Prefer structs for small immutable data such as points, money and ranges; use classes for things with identity or shared mutable state.

sizeof(Point) reports the inline size in bytes (two Int32 fields are 8). Structs avoid a heap allocation, which matters in tight loops over many small values.

structs

struct Point
  property x : Int32
  property y : Int32

  def initialize(@x, @y)
  end

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

class Counter
  property n = 0
end

def bump(p : Point)
  p.x += 1
  p.x
end

a = Point.new(1, 2)
b = a
b.x = 10
puts a.x
puts b.x
puts bump(a)
puts a.x

ca = Counter.new
cb = ca
cb.n = 10
puts ca.n

puts Point.new(1, 2) == Point.new(1, 2)
puts Counter.new == Counter.new
puts (a + Point.new(2, 2)).x

pts = [Point.new(0, 0)]
pts[0].x = 5
puts pts[0].x
p = pts[0]
p.x = 5
pts[0] = p
puts pts[0].x
puts sizeof(Point)
Match this when you type.

Quiz

After b = a with a struct, what does changing b.x do to a?

Quiz

Why does pts[0].x = 5 leave the array element unchanged for a struct?

Quiz

How do two structs with the same fields compare with ==?

Quiz

Which is the better fit for a struct?

Check

Match the still for: Structs and value semantics.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.