Declare Go variables using var
Create a named value
A variable is a named storage location with a type. A declaration using var name type = value gives it an initial value and a type. For example, int represents integer values and string represents text. A variable can later receive another value of an appropriate type; its type does not change.
package main
import "fmt"
func main() { var quantity int = 3 var product string = "Pen" fmt.Println(product, quantity)}The output is Pen 3. Use the type after the variable name. var int quantity = 3 reverses Go syntax and is invalid. If an initial expression is supplied, the type may be omitted and inferred, as in var quantity = 3. If no expression is supplied, the type is required and the variable starts at its zero value (lesson 6).
Group related declarations
package main
import "fmt"
func main() { var ( width = 4 height = 2 ) fmt.Println(width, height)}The output is 4 2. Each declaration in the group uses its own type or initializer. Unlike short declarations, var is also allowed outside a function at package scope. A local variable must be used in ordinary Go compiler builds; avoid declaring unused names.
Try it locally
Use var to declare a string named city with value Oslo and an int named days with value 4. Print them on one line. Expected: Oslo 4. Hint: the type follows the name.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tokens and Declarations 03: Declare Go variables using var
Check the lesson objective before moving on.
Which declaration specifies the type correctly?
Can var declarations appear at package scope?