Lexical elements: Keywords, Operators and punctuation

January 13, 2023

Keywords

The following keywords are reserved and may not be used as identifiers.

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var

Operators and punctuation

The following character sequences represent operators (including assignment operators) and punctuation:

+    &     +=    &=     &&    ==    !=    (    )
-    |     -=    |=     ||    <     <=    [    ]
*    ^     *=    ^=     <-    >     >=    {    }
/    <<    /=    <<=    ++    =     :=    ,    ;
%    >>    %=    >>=    --    !     ...   .    :
     &^          &^=          ~

There’s not a lot to say about these rather dull lists of keywords and operators, except maybe to point out some conspicuous omissions.

One of the design goals for the Go programming language is simplicity. Both in terms of the language itself (i.e. a simple syntax), and in terms of usability (i.e. one way to do things). This has lead to some (in?)famous “corner cutting”, which often annoys many newcomers. Although I, and many other more seasoned Go developers, have come to appreciate many of these choices. Let’s look at a few.

  • while

    How do you do an infinite loop without a while keyword? Why, with a for loop with no closing condition!

  • throw and try / catch

    Go doesn’t have exceptions, so there are no try / catch keywords. Instead, it treats errors as first-class values, which, of course, we’ll be discussing in due time.

    Go also has panic, which looks a bit like throw, but has important differences we’ll get to.

  • elseif or elsif

    No need for another keyword when we can just use the combination of the existing else and if as in else if.

A large number of other concepts that are implemented as keywords in other languages also exist in Go, but via other mechanisms. For example, there’s no export keyword in Go, because exported vs non-exported symbols are handled via capitalization. There’s no implements keyword, because Go’s “Duck typing” provides other means to determine which types implement an interface. Etc.

Quotes from The Go Programming Language Specification, Version of June 29, 2022