iyi

Playground · Generics · 30 of 33

generic-types

Generic types: a struct with a type parameter.

samples/tour/generic-types.iyi · generic-types.wasm · 130 KB
# Generic types: a struct with a type parameter.

struct Stack(T)
  def initialize
    @items = [] of T
  end

  def push(item : T) : Nil
    @items << item
  end

  def pop : T?
    @items.empty? ? nil : @items.pop
  end

  def size : Int32
    @items.size
  end
end

numbers = Stack(Int32).new
numbers.push(1)
numbers.push(2)
puts numbers.size
puts numbers.pop
puts numbers.pop
puts numbers.pop

words = Stack(String).new
words.push("iyi")
puts words.pop

# A trait can be implemented for the generic type once, for every T.
trait Describe
  abstract def describe : String
end

impl Describe for Stack(T) forall T
  def describe : String
    "a stack of #{size}"
  end
end

numbers.push(5)
puts numbers.describe
puts words.describe
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 generic-types.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

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

sh, after installing
$ iyi run generic-types.iyi