Crystal Pass Variable by Reference or Value

How do I choose how to pass a variable by value or reference using Crystal ?

Exemple : I would like to pass a Struct by reference and not by Value ( the documentation explains that it is passed by Value while classes are passed by reference ).

1 Answer

You can't choose. You just need to keep in mind that object which is a Value passed by value, other objects passed by reference.

Struct is a Value and passed by value. You should prefer using structs for immutable data types. However, mutable structs are still allowed in Crystal and actually this example demonstrates how to mutate it using a method. In short:

struct Mutable
  property value

  def initialize(@value : Int32)
  end
end

def change(mutable)
  mutable.value = 2
  mutable
end

mut = Mutable.new 1
mut = change(mut)
mut.value # => 2
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest