abstract struct Struct
Overview
Struct
is the base type of structs you create in your program.
It is set as a struct's superstruct when you don't specify one:
struct Foo # < Struct
end
Structs inherit from Value
so they are allocated on the stack and passed
by value. For this reason you should prefer using structs for immutable
data types and/or stateless wrappers of other types.
Mutable structs are still allowed, but code involving them must remember that passing a struct to a method actually passes a copy to it, so the method should return the modified struct:
struct Mutable
property value
def initialize(@value : Int32)
end
end
def change_bad(mutable)
mutable.value = 2
end
def change_good(mutable)
mutable.value = 2
mutable
end
mut = Mutable.new 1
change_bad(mut)
mut.value # => 1
mut = change_good(mut)
mut.value # => 2
The standard library provides a useful record
macro that allows you to
create immutable structs with some fields, similar to a Tuple
but using
names instead of indices.