I was curious about the Python connection because multiple comments mentioned it, but I’ve worked on multiple Python projects over the past dozen-ish years and never seen that operator.
Turns out it was introduced in 3.8, released in 2019, so it was much too late to inspire Go, and most of the projects I’ve worked on were written to target an earlier Python version. It also has a substantially different meaning than in Go.
I don’t know if there’s an “official” rationale for the Go syntax, but :=
is a fairly common (but not ubiquitous) math notation meaning “define the thing on the left to be equal to the expression on the right”, i.e. to distinguish it from the other use of =
, i.e. “the expression on the left must be equal to the expression on the right.” Go’s usage matches this mathematical meaning of introducing a new variable definition pretty well.
That is absolutely not true.
foo := <expr>
is a statement in Go, full stop. Just try something trivial like assigning to the output of:=
: https://go.dev/play/p/nPINGc7LO8BIt’s true that
if
andfor
let you use:=
but don’t let you usevar
, but you still can’t use the result of the assignment directly. So for instance you needif foo := <expr>; foo { ... }
rather than justif foo := <expr> { ... }
.