Not sure where they got that Nim has a walrus operator. Maybe because the syntax resembles Python? That'd make sense.
Not sure where they got that Nim has a walrus operator. Maybe because the syntax resembles Python? That'd make sense.
a := b
the `:=` looks vaguely like a walrus. The most common reference language seems to be Python [1]. The usage is for making assignment remain an expression, so you can do stuff like area = (width := get_width()) * (height := get_height())
or something, and have the top-level expression remain valid since the sub-expressions are assignments that remain expressions, i.e. the assigned value is also the result of the expression.Since it was introduced, I have been looking but there has been only a handful of times where I could use it to write clearer code.
I'm curious if anyone actually likes it.
edit: A quick search shows that I do use it regularly in while loops, e.g.:
while result := my_fun():
... if (config_fn := base_dir / "config").exists():
...
is just a tiny bit shorter than this: config_fn = base_dir / "config"
if config_fn.exists():
...
but if you do this enough times (if you are handling a lot of possible errors / missing data, etc.) it can definitely shorten the code.In other contexts, parens are a good indication it's time for a new line.
But I can agree something like this does look clean and clear:
if value := obj.get("key"):
...I used it a small handful of times. But it also seems like quite a source of footguns. Many examples here: https://github.com/satwikkansal/wtfpython rely on the misuse of the walrus operator.
https://en.wikipedia.org/wiki/Assignment_(computer_science)#...
That always made more sense to me than = for assignment and more =s for different kinds of equality, but in the end this syntax discussions are always just bike-shedding.