I noticed something while writing the last two sections on Integer literals and Floating-point literals, and I’m curious if anyone else noticed.
There’s no way to express a negative integer or floating-point literal!
If we look specifically at the definition of an decimal literal in EBNF format, we see:
decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
Notably, we do not see this:
decimal_lit = [ "+" | "-" ] "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
Does this mean Go doesn’t support negative numbers? Well, obviously not. What use is a programming language without negative numbers?
Does it mean it doesn’t allow assigning negative values directly to constants or variables? No, that’s easily disproven as well.
So what gives?
The +
and -
signs are interpteted by Go as Unary operators (there are a few others as well).
So what that means is when you write
var myInt = -30
You have not written a negative integer literal (-30
). Rather, you’ve written an integer literal (30
), preceeded by the unary operator -
which negates it value.
Remember that one for your next Go Pub Quiz night!