Understanding variables in Go
A variable is a symbolic name or identifier used to store or hold values of a different data type and an associated name. A variable name to reference the values stored within a program. Specific Data type in Go includes string, integer, Boolean, float, array, slice, interface, and maps. A data type is a set of values and allowable operands on those values. In Golang, we can infer the data type from the right side of the assignment.
Variable naming styles and rules followed in Go
The naming of variables is so flexible, but there are some styles and rules to keep in mind:-
- Variable names must only be one word (as in no spaces). example of valid naming:-
userName
,userAge
,userEmail
- Variable names must be made up of only letters, numbers, and underscores (_). e.g user_Name
- Variable name terms cannot begin with a number. e.g userName1
Different ways to declare variables in Go
In Go, we can declare a variable in two ways which include:-
- Using
var
keyword variable declaration - Using
:=
shorthand variable declaration
Method-1: Using var keyword variable declaration
The most explicit way of declaring any variable is by using var
keyword, for example
var x int = 10
If the type on the righthand side of the =
is the expected type of your variable, you can leave off the type from the left side of the =
. Since the default type of an integer literal is int
, the following declares x to be a variable of type int
:
var x = 10
If you want to declare a variable and assign it the zero value, you can keep the type and drop the =
on the righthand side:
var x int
You can declare multiple variables at once with var
, and they can be of the same type:
var x, y int = 10, 20
all zero values of the same type:
var x, y int
or of different types:
var x, y = 10, "hello"
There’s one more way to use var. If you are declaring multiple variables at once, you can wrap them in a declaration list:
var (
x int
y = 20
z int = 30
d, e = 40, "hello"
f, g string
)
Method-2: Using := shorthand variable declaration
Go also supports a short declaration format. When you are within a function, you can use the :=
operator to replace a var
declaration that uses type inference. The following two statements do exactly the same thing: they declare x to be an int with the value of 10:
var x = 10 x := 10
Like var, you can declare multiple variables at once using :=. These two lines both assign 10 to x and “hello” to y:
var x, y = 10, "hello"
x, y := 10, "hello"
The := operator can do one trick that you cannot do with var: it allows you to assign values to existing variables, too. As long as there is one new variable on the lefthand side of the :=, then any of the other variables can already exist:
x := 10
x, y := 30, "hello"
There is one limitation on :=
. If you are declaring a variable at package level, you must use var
because :=
is not legal outside of functions.
See the following example below.
// main.go
package main
import "fmt"
func main() {
name := "George "
age := 25
fmt.Printf("My name is %s , am %d years old. \n", name, age)
}
Output:
$ go run main. go
My name is George, am 25 years old.
The example above shows two (name and age) variables declared using shorthand notation.
Variable scope definition in Go
Variable scope refers to the particular places it is accessible from within the function or block level, a package of a given program. A package-level variable is defined outside of any function in a program. It is accessible throughout the package and can only be of var
declaration since the shorthand :=
operator is not being available outside the function. The scope of the variable is determined during compilation time. Variables can be called within the block of code in which it is defined.
In Golang scope of variables can be divided into two categories which depend on where the variables are declared:
- Local variables (Declared inside a block or function)
- Global variables (Declared outside a block or function)
Local variables
- It's also known as block variables.
- These are variables declared inside a function or a block, thus the variable is not accessible outside the function or block.
- These variables can also be declared inside the for loop inside a function.
- There will be a compile-time error if these variables are declared twice with the same name in the same scope.
- These variables can be accessed by the nested code blocks inside a function.
- These variables don’t exist after the function’s execution is over.
- A variable that is declared inside a loop body will not be visible to the outside of the loop body.
- The variable which is declared outside the loop is also accessible within the nested loops.
- The local variable will be accessible to loop and function inside that function.
Example of a local variable scope:
// Program to demonstrate local variables scope
// main.go
package main
import "fmt"
func add(a int, b int) int {
// local variables
var sum int = 2
return (a + b - sum)
}
func main() {
x := 20
y := 40
results := add(x, y)
fmt.Println("results ", results)
// cannot access sum out of its local scope
fmt.Println("Sum is", sum)
}
Output
./prog.go:18:24: undefined: sum
Go build failed.
Explanation:- The sum variable is local to the add()
function, so it can only be accessed within the function. That’s why we get an error when we try to access the function from the main()
. To fix this issue, we can either return the value of the local variable or assign it to another variable inside the main function. Or we can make the variable sum global.
Local variable source code from go playground
Global variables
- The global variables are defined outside of the function in the go program.
- Functions can be accessing these variables anywhere in the go program.
- The variables are accessible by all functions defined in the go program.
- In a nested function is declared, then the parent function's local variable will act as a global variable for his child's function.
- If the global variable and local variable have the same name within a function in the go program. Still, in this case, the function will prioritize his local variable over the global variable and perform all operations on his local variable's value.
- These are declared at top of the program outside all functions or blocks.
- These can be accessed from any portion of the program.
- These are available throughout the lifetime of a program means they will exist at the end of the execution process of the go program.
Example of a global variable scope
// Program to illustrate global variable scope
// main.go
package main
import "fmt"
// declare global variable before main function without initial values
var sum int
func add(a int, b int) int {
// local variable
sum = 4
return (a + b + sum)
}
func main() {
x := 20
y := 30
results := add(x, y)
// print results
fmt.Printf("Results are %v \n", results)
// can access sum
fmt.Printf("Sum value is %v", sum)
}
Output
Results are 54 Sum value is 4
Explanation:- Since we have declared sum as global variable using var keyword, we can access the sum variable from inside the main()
function. Although you may notice that we have just declared the type of var sum
while the actual value assignment is happening inside func add
but still var sum
will be considered as global variable.
global variable source code from go playground
"var" vs ":-" in golang and when to use them in your code?
- When initializing a variable to its zero value, use
var x int
. This makes it clear that the zero value is intended. - When assigning an untyped constant or a literal to a variable and the default type for the constant or literal isn’t the type you want for the variable, use the long
var
form with the type specified. While it is legal to use a type conversion to specify the type of the value and use:=
to writex := byte(20)
, it is idiomatic to writevar x byte = 20
. - Because
:=
allows you to assign to both new and existing variables, it sometimes creates new variables when you think you are reusing existing ones. In those situations, explicitly declare all of your new variables withvar
to make it clear which variables are new, and then use the assignment operator (=
) to assign values to both new and old variables.
Summary
- The case and default keywords also introduce a new scope even though no curly braces are involved.
- The location where a variable is declared determines which variable scope it’s in.
- An opening curly brace { introduces a new scope that ends with a closing brace }.
- Variables declared on the same line as a for, if, or switch is in scope until the end of that statement.
- A wide variable scope is better than a narrow scope in some situations—and vice versa.
- A variable declared within an inner scope having the same name as the variable declared in the outer scope will shadow the variable in the outer scope.
References
variable scope in golang
scope-of-variable-go