Go is generally a minimal language as far as both language keywords and features go. It's not quite down to Scheme level minimalism , it's far more pragmatic than that, but it does try to be small. In among this smallness, one thing may stand out; I'm thinking of the increment and decrement statements , '
i++
' and '
j--
'.
There's strictly speaking no need for these to exist. Since Go makes them statements instead of operators, they are exactly equivalent to '
i += 1
' and '
j -= 1
'. Yet not only do they exist, but if you run
golint
over code that contains the assignment versions it will suggest simplifying them to increment and decrement:
fred.go:4:2: should replace i += 1 with i++
I don't know why Go has decided to go this way, but I do see at least one advantage to using increment and decrement statements instead of assignments: increment and decrement make your intentions clear . Anyone (including yourself) who later reads your code knows that it's not accident or happenstance that you're moving by 1s; it's fully intentional. If there's a bug and this is not the right increment, you may need to look at larger sections of the algorithm, not just change a constant and see if it works; similarly if you now need to move in different strides.
In a related thing, it's also more visually distinctive. Increment and decrement statements stand out, partly because they don't have an
=
, and probably read faster since you don't have to parse the number when scanning them.
This wouldn't be enough to justify them in a minimal language, but in a pragmatic language like Go I'm glad they exist. Incrementing and decrementing things is common enough that it's nice to have a compact and distinctive idiom that makes your intentions clear.
Sidebar: The operator versus statement distinction here
C has increment and decrement operators . You can use
++
and
--
in any context just like other operators, so you can write:
i = j++ * 10 - fred(k++);
And other equally complicated expressions. Often the complications arise with pointers in various contexts.
Go has increment and decrement only as statements , not as operators (and this is deliberate ). That line is invalid Go; as statements,
++
and
--
must occur on their own, not as part of expressions in assignment statements, function calls, and so on.