Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crystal pass variable by reference or value

Tags:

crystal-lang

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 ).

like image 850
Matthieu Raynaud de Fitte Avatar asked Oct 07 '17 23:10

Matthieu Raynaud de Fitte


1 Answers

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
like image 140
Vitalii Elenhaupt Avatar answered Nov 10 '22 09:11

Vitalii Elenhaupt