Is it possible to overload `:=`?

This was my first attempt to overload the := operator:

julia> (:=)(x, y) = x + y
ERROR: syntax: invalid identifier name ":="

This was my second attempt:

julia> var":="(x, y) = x + y
:= (generic function with 1 method)

julia> 1 := 2
ERROR: syntax: unsupported assignment operator ":="

The := operator is listed as an assignment operator in the Julia parser, so it seems like there ought to be a way to get this to work. Does anyone know if it’s possible? (I mean outside of a macro.)

2 Likes

I don’t think so. You can’t overload assignment operators in Julia. I think := is currently only usable via macros.

3 Likes

You can get partway there using the COLON EQUALS (U+2254) unicode character (typed in Julia as \coloneq<TAB>):

julia> ≔(x,y) = x + y
≔ (generic function with 1 method)

julia> ≔(2, 5)
7

But you can’t use it as an infix operator:

julia> 2 ≔ 5
ERROR: syntax: unsupported assignment operator "≔"
2 Likes

Yeah, I looked at the Unicode character, but in most fonts it seems really hard to visually distinguish it from a regular =.

I agree.

1 Like

FWIW:
:\_=<tab>
produces the symbol:
:₌

2 Likes