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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.

You Might Also Like