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:

var i int 

Thinking back to the last section and the topic ofinference, 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:

var i int 
 
func main() {
	i = 42
}

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

func main() {
	i := 42
}
  • Can be used instead of varonly inside of functions
  • We don’t need to and can’t provide a data type
  • Can’t be used at the package level
  • Outside of functions, everything begins with a keyword

Constants

Constants are variables whose values can’t be changed. To make this clear, let’s first change the values of some variables.

By using =we can assign a new value to a variable - no matter if it was created using varor :=:

var i int = 40
i = 20
 
g := 10
g = 5

Creating a constant using constworks the same as using var- just exchange the keyword:

const i int = 40

Now, the value of ican’t be changed - it is constant.

To create constants, we need to use the constkeyword explicitly.

Next Chapter: Functions