Struct pass-by-value


For immutable structs this is not relevant but when the struct is mutable you have to remember that it is passed by value to functions. That is, the function receives a copy of the external struct. Any changes made to the struct inside the function will be lost when you leave the function.

examples/struct/struct_pass_by_value.cr
struct Person
  property name : String
  property email : String

  def initialize(@name, @email)
  end
end

def set_email(pers : Person)
  pers.email = "fake@address.com"
  p! pers
end

prs = Person.new("Foo", "me@foo.bar")
p! prs
p! prs.name
p! prs.email

puts ""

set_email(prs)

puts ""
p! prs
p! prs.name
p! prs.email

prs # => Person(@name="Foo", @email="me@foo.bar")
prs.name # => "Foo"
prs.email # => "me@foo.bar"

pers # => Person(@name="Foo", @email="fake@address.com")

prs # => Person(@name="Foo", @email="me@foo.bar")
prs.name # => "Foo"
prs.email # => "me@foo.bar"