Crystal pass variable by reference or value
Asked Answered
S

1

6

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

Suave answered 7/10, 2017 at 23:39 Comment(0)
W
8

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
Williawilliam answered 8/10, 2017 at 6:58 Comment(6)
Using pointers outside bindings or special performance optimizations certainly isn't best practice.Sharpnosed
@JonneHaß thanks, added your comment to the answer in boldWilliawilliam
It's not just bad practice but actually unsafe code!Eyelet
I think that mentioning unsafe pointers in this example is a bad idea. You'd be better off introducing a class wrapper which forwards all calls to the inner Value type.Stratiform
@RX14 honestly, i think this is a problem of the language, not the example itself. OP is free to choose the way to code and is responsible for it. But I am okay to remove it from the answer.Williawilliam
Mutable struct has an issue here github.com/crystal-lang/crystal/issues/4933Importunacy

© 2022 - 2024 — McMap. All rights reserved.