Skip to content

Latest commit

 

History

History
79 lines (59 loc) · 1.91 KB

2.04.md

File metadata and controls

79 lines (59 loc) · 1.91 KB

2.04 The Var Keyword

We saw the short declaration operator and how it can be used within code blocks. What about when we have a variable we want accessed in a wider scope?

package main

import (
	"fmt"
)

func main() {
	x := 42 + 7		/* the scope of x is from here down */
	y := "James Bond"	/* the scope of y is from here down */
	fmt.Println(x)
	fmt.Println(y)
	x = 50
	fmt.Println(x)
}

I won't be able to access a variable before it is declared. Nor outside of its scope.

package main

import (
	"fmt"
)

func main() {
	x := 42 + 7
	y := "James Bond"
	fmt.Println(x)
	fmt.Println(y)
	x = 50
	fmt.Println(x)
}

func foo() {
	fmt.Println(x)	/* x is out of scope here */
}

We get the error tmp/sandbox324213631/main.go:17: undefined: x. Line 17 is trying to acess x, and it cannot.

Sometimes, we are going to want a variable scope larger than the code block. If I want scope that is at the package level, I can use var. We can ensure our language is correct for the keywords by checking out keywords in the Go documentation.

The var keyword allows us to create a variable. Let's add the variable z and set its value to 21.

package main

import (
	"fmt"
)

var z = 21

func main() {
	x := 42 + 7
	y := "James Bond"
	fmt.Println(x)
	fmt.Println(y)
	x = 50
	fmt.Println(x)
	fmt.Println(z) /* z is in scope here as well */
}

func foo() {
	fmt.Println(z)	/* z is in scope anywhere throughout the package */
}

Here's a good coding practice tip: Always use the short declaration operator inside code block to declare and assign a value to a variable. And if you need package level scope, use var.

Some terminology: curly braces {}, parentheses ()

Recapitulate: To create a variable with a package level scope, we use var, the variable name, the equals operator =, and the value we wish to assign it, e.g. var greeting = "Hello there"