Skip to content

Instantly share code, notes, and snippets.

@Patrikios
Created February 20, 2022 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Patrikios/c5b0392bb01fd52ca349ae1b735f2901 to your computer and use it in GitHub Desktop.
Save Patrikios/c5b0392bb01fd52ca349ae1b735f2901 to your computer and use it in GitHub Desktop.
Passing by reference an passing by value in julialang
#= assignment of a function to a new name
- is shallow copy of a function
- in programming parlance: done by reference
=#
f(x) = 2x
g = f
g #f (generic function with 1 method)
g(2) #4
f(x) = 4x
g(2) #8
# alter variable by reference
# by use of Ref keyword
f(x::Ref) = x[] = 4
a = Ref{Int}(0)
f(a)
(a[], typeof(a[])) #(4, Int64)
# use of struct (somehow more idiomatic?? @ https://discourse.julialang.org/t/how-to-modify-value-of-scalar-argument-passed-to-function-so-that-it-persists-in-calling-function/27151/5)
f(x) = x.value = 1000
mutable struct s
value::Int64
s() = new(1)
end
s_instance = s()
s_instance.value |> typeof
f(s_instance)
s_instance.value # 1000
# wrapping the value into an array
f(x::Vector) = x[1] = 4
x = [0]
x
f(x)
x
# 1-element Vector{Int64}:
# 4
# use of global variable
# Note! Variable 'a' has to be initilised before the function definition
a = 0
function f(a::Int)
global a = 1000
return nothing
end
f(a)
a #1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment