3. Variables in Go — A Book of Go

Louis Petrik
2 min readMay 14, 2024
Source: the author

Now, let’s talk about variables.

Variables can be declared with the keyword var:

  • Can be a list of variables: `var a, b, c int
  • Can be used within functions (used at package or function level)
  • A vardeclaration can have an initialisation: var i int = 1

Yet, var can also be used without directly defining the data (initialization). A declaration alone looks like this:

Thinking back to the last section and the topic of inference, a standalone declaration, as in the example, is the exception to the rule. In this case, we need to provide a data type, as Go can’t infer the type from the value (as we don’t provide a value).

Later in our code, an integer value can be assigned to our variable like this:

Aside from var there is also :=. This syntax can be used to declare and initialize variables within functions. It looks like this:

  • Can be used instead of varonly inside of functions
  • We don’t need to and can’t provide a datatype
  • Can’t be used at the package level
  • Outside of functions, everything begins with a keyword

Constants

--

--