Use var keyword to declare a variable. Here are the rules:
// Valid identifiers: _geeks23 geeks gek23sd Geeks geeKs geeks_geeks // Invalid identifiers: 212geeks if default
Here is an example:
package main
import "fmt"
func main() {
var name = "GeeksforGeeks"
}
The identifier represented by the underscore character(_) is known as a blank identifier. It is used as an anonymous placeholder instead of a regular identifier, and it has a special meaning in declarations, as an operand, and in assignments.
To mention datatype of the variable write the type after the variable name and seperate them with a space.
var name string, age int var c, python, java bool
Here is an example:
package main
import "fmt"
// package level variables
var c, python, java bool
func main() {
// function level variable
var i int
fmt.Println(i, c, python, java)
}
It will produce the following output:
0 false false false
A var declaration can include initializers, one per variable. If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = true, false, "no!"
fmt.Println(i, j, c, python, java)
}
The output of the above code is:
1 2 true false no
The first value true goes to the first variable c, the second value false goes to the second variable python, and the last value "no" goes to variable java.
The number of variables on the left side of the =, and the number of values on the right side of the =, must be same. Otherwise you will get an exception.
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
}
Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.
Variables declared without an explicit initial value are given their zero value.
0 for numeric types,false for the boolean type, and"" (the empty string) for strings.
package main
import "fmt"
func main() {
var i int
var f float64
var b bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, b, s)
}
Output:
0 0 false ""