Pass by reference problem


#1
julia> type RR
           x::Int
       end

julia> function tt(x,y)
           if (x+=y) > 0
               x
           else
               y
           end
       end
tt (generic function with 1 method)

julia> import Base:+,>,<

julia> +(a::RR,b::RR) = RR(a.x+b.x)
+ (generic function with 181 methods)

julia> >(a::RR,b::Int) = a.x > b
> (generic function with 3 methods)

julia> <(a::Int,b::RR) = a<b.x
< (generic function with 60 methods)

julia> x = RR(3)
RR(3)

julia> y = RR(5)
RR(5)

julia> tt(x,y)
RR(8)

julia> x
RR(3)

even though the returning result is RR(8) but the passed argument x is not changed? Why is that?
Thanks


#2
+(a::RR,b::RR) = RR(a.x+b.x)

constructs a new instance. You’d have to do +(a::RR,b::RR) = a.x+=b.x but I strongly suggest that you don’t do that as it is not what + is supposed to do. Also, as your example stands, you don’t gain anything from in-place modification versus just making RR a immutable type and doing it normally.

If your type would be more of a container, you’d do it with the broadcast machinery.


#3

So basically assignment works as an identifier points to something. Not a reference, for a reference you need to access it fields.

What about broadcast ? Can you give me an example?

Thanks


#4

Broadcasting changed recently with #23939, which has a nice writeup. You might want to look at that. But note that is the development version. I would wait for that to trickle into stable though, it became much less complex than previously.

Also, use struct instead of type, which is previous syntax and will be removed. It has the extra advantage of being immutable by default (unless you ask for mutable struct), so it encourages the kind of approach that @mauro3 suggested.