juliavariable-assignmentpython-assignment-expression

Equivalent of Python's Walrus operator (:=) in Julia


In python you can write

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

is there an equivalent feature in Julia?


Solution

  • The value of assignment is always passed through (because everything is an expression) in julia, so you could write

    if (n = length(a)) > 1
        println("List is too long ($(n) lements, expected <= 10)")
    end
    

    to avoid confusion with == and to make the variable local, you can use the local keyword. This is then equivalent to a walrus operator

    if (local n = length(a)) > 1
        println("List is too long ($(n) lements, expected <= 10)")
    end