...

/

Functions and Scopes

Functions and Scopes

Understand the scope of variables and learn to create functions in Go.

We'll cover the following...

Scopes

A scope is a program region where we can access a variable. We have local and global variables in Go. We can access local variables within the blocks we define them in. Global variables are accessible throughout the program.

Press + to interact
package main
import "fmt"
func main() {
// local variable
var eggs,chickens int
eggs = 3
chickens = 7
fmt.Printf ("eggs = %d, chickens = %d\n", eggs,chickens)
}

Let’s see an example of global variable declaration below:

Press + to interact
package main
import "fmt"
// global variable
var months int = 11
func main() {
fmt.Printf ("months = %d\n", months)
}

It’s possible to have the same name for a local and a global variable, but the global variable becomes inaccessible in the scope of that local variable. The scope of the local variable starts from the line of declaration of that variable, and ends at the enclosing right brace, ...

Access this course and 1400+ top-rated courses and projects.