Structs in Crystal

Our example demonstrates how to use structs to group data together forming records. Here’s the full source code translated to Crystal.

struct Person
  property name : String
  property age : Int32
end

def new_person(name : String) : Person
  person = Person.new(name: name)
  person.age = 42
  person
end

# Creating a new struct
puts Person.new(name: "Bob", age: 20)

# Initializing a struct with named fields
puts Person.new(name: "Alice", age: 30)

# Omitted fields will be zero-valued
puts Person.new(name: "Fred")

# Getting a pointer to the struct using &
ann = Person.new(name: "Ann", age: 40)
puts &ann

# Using a constructor function
puts new_person("Jon")

# Accessing struct fields with a dot
s = Person.new(name: "Sean", age: 50)
puts s.name

# Using dots with struct pointers
sp = &s
puts sp.value.age

# Structs are mutable
sp.value.age = 51
puts sp.value.age

# Anonymous structs
dog = {name: "Rex", is_good: true}
puts dog

To run the program, save the code in a file (e.g., structs.cr) and use the Crystal compiler to execute it.

$ crystal run structs.cr
{Bob, 20}
{Alice, 30}
{Fred, 0}
@Person@0x7ffee36d9c80
@Person@0x7ffee36d9c90
Sean
50
51
{name: "Rex", is_good: true}

Now that you’ve seen how to use structs in Crystal, you can use this concept to group related data together in your programs. Let’s move on to learn more about the language.