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 ).
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 ).
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
class
wrapper which forwards all calls to the inner Value
type. –
Stratiform © 2022 - 2024 — McMap. All rights reserved.