Declaration of variable
var <Variable_Name> <Variable_Type> <Assignment operator> <Variable Value>
var x string = "xyz"
OR
var <Variable_Name> <Variable_Type>
<Variable_Name> <Assignment operator> <Variable Value>
var x string
x = "xyz"
OR
<Variable_Name> <:> <Assignment operator> <Variable Value>
x := "Hello World"
OR
const <Variable_Name> <Variable_Type> <Assignment operator> <Variable Value>
const x string = "Hello World"
Note - instead of using the var keyword we use the const keyword
Notice the : before the = and that no type was specified.
The type is not necessary because the Go compiler is able to infer the type based on the literal value you assign the variable.
(Since you are assigning a string literal, x is given the type string) The compiler can also do inference with the var statement.
Example
package main
import "fmt"
func main() {
var x string
x = "Hello World"
// Or use
// var x string = "Hello World"
fmt.Println(x)
}
var x string = "hello"
var y string = "world"
fmt.Println(x == y)
This program should print false because hello is not the same as world.
Constants
const x string = "Hello World"
Go also has support for constants. Constants are basically variables whose values cannot be changed later.
They are created in the same way you create variables but instead of using the var keyword we use the const keyword:
package main
import "fmt"
func main() {
const x string = "Hello World"
fmt.Println(x)
}
Defining Multiple Variables
Go also has another shorthand when you need to define multiple variables:
var (
a = 5
b = 10
c = 15
)
Use the keyword var (or const) followed by parentheses with each variable on its own line.
Defining Special Variables ("_")
underscore ("_") is a special variable. The Go compiler won't allow you to create variables that you never use. So while we use range for arrays then assign the value to "_" you do not want to use.
A single _ (underscore) is used to tell the compiler that we don't need this
Example
var total float64 = 0
for i, value := range x {
total += value
}
fmt.Println(total / float64(len(x)))
$ go run tmp.go
# command-line-arguments
.\tmp.go:16: i declared and not used
var total float64 = 0
for _, value := range x {
total += value
}
fmt.Println(total / float64(len(x)))
Next.