iyi

Playground · Methods and traits · 23 of 33

traits

A trait: a set of methods a type promises to have.

samples/tour/traits.iyi · traits.wasm · 156 KB
# A trait: a set of methods a type promises to have.

trait Shape
  # `abstract def` is a requirement. Every implementer must define it.
  abstract def area : Float64
end

struct Circle
  def initialize(@radius : Float64)
  end
end

struct Square
  def initialize(@side : Float64)
  end
end

# `impl Trait for Type` is the one way to give a type a trait. The impl
# lives next to the trait or next to the type, never anywhere else.
impl Shape for Circle
  def area : Float64
    3.14159 * @radius * @radius
  end
end

impl Shape for Square
  def area : Float64
    @side * @side
  end
end

puts Circle.new(1.0).area.round(2)
puts Square.new(2.0).area

# Leave a requirement out and the compiler refuses the impl, naming the
# missing method. Try removing `area` from one of the impls above.
output
Press Run.

recorded with iyi 0.18.0 (built on Crystal 1.22.0-dev [2a9653052] (2026-10-18)) · Linux 7.0.0-38-generic x86_64, QEMU Virtual CPU version 2.5+ · 2026-10-19

You can type in the pane: nothing here compiles, so what you type cannot run, and the page says which bytes it is running the moment the text stops being the recorded file. There is no standard input, no filesystem and no threads on this target, and one sample fails on purpose for exactly that reason.

Run executes traits.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

Copy the program into traits.iyi, change something, and run it. Only a compiler on your own machine can run what you wrote.

sh, after installing
$ iyi run traits.iyi