Crystal Notes: Structs
Published: 2021-08-04
Intro
Structs have a similiar syntax to a Class and are used to hold data.
Intro
crystal
# Define an Struct.
struct Stuff
@stuff : String
property stuff
def initialize(@stuff)
end
def print
puts(@stuff)
end
end
# Instatiate the Stuff struct.
s = Stuff.new("my stuff")
# Use the print method.
s.print # => my stuffConsiderations
- Structs are created on the stack and are passed by value.
- Structs are best suited for small amounts of immutable data.
- Structs can be mutable, since values are copied, the behaviour is different from a class.
Links
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/syntax_and_semantics/structs.html