Variables
| Declare with var | |
| Short := declaration | |
| Zero values | |
| Naming rules |
Declare with var
The var keyword declares a variable with an explicit type and an optional initial value.
For the full reference see the article
declare variables
and use the pattern below as the default form.
package main
import "fmt"
func main() {
var name string = "Gopher"
var age int = 5
var active bool = true
fmt.Println(name, age, active)
}
go run .
Gopher 5 true
Short := declaration
Inside functions, the short form with := declares the variable and infers its type from the value on the right side.
It keeps code compact, but it cannot be used outside functions or without a new value.
package main
import "fmt"
func main() {
name := "Gopher"
age := 5
ratio := 0.5
fmt.Println(name, age, ratio)
}
go run .
Gopher 5 0.5
Zero values
Every declared variable already holds a zero value before the first assignment: 0 for numbers, false for booleans, and an empty string for text.
That is why the program below prints sensible output even though active and title are never assigned.
package main
import "fmt"
func main() {
var count int
var active bool
var title string
fmt.Println(count, active, title + "empty")
}
go run .
0 false empty
Naming rules
Names may contain letters, digits, and underscores, must start with a letter or an underscore, and are case sensitive, so age and Age are different variables.
Go convention uses camelCase for local variables, CamelCase for exported identifiers, and short names such as i or n for tiny scopes.
Reserved keywords cannot serve as names, and clear names beat short ones everywhere except loop counters.
Next: Constants
Article author: Arthur Isaev