Search⌘ K
AI Features

Functions and Scopes

Learn how to work with functions and variable scopes in Go, including defining local and global variables, passing parameters, and returning values. Understand string handling with Go's libraries to enhance your programming skills for API development.

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.

Go (1.16.5)
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:

Go (1.16.5)
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, ...