Infer Go variable types with :=
Short declarations inside functions
Inside a function, name := value declares a variable and infers its type from the initial value. Here count is an int and label a string. You do not write var or an explicit type with :=. The inferred type remains fixed.
package main
import "fmt"
func main() { count := 5 label := "Boxes" fmt.Println(label, count)}The output is Boxes 5. For an untyped integer literal such as 5, the default type is int; for a string literal, it is string. Use var if you need an explicit type or a package-level variable.
At least one new name
package main
import "fmt"
func main() { count := 5 count, label := 6, "Boxes" fmt.Println(label, count)}The second line is legal because label is new and count already exists in the same block with the same type. The original count receives 6. Writing count := 6 alone in that block would fail with no new variables. Use count = 6 to update it. A nested block can introduce a distinct variable with the same name; scope is taught later.
Try it locally
Declare total with := and value 9, then use a short declaration to update total to 10 and introduce unit with value kg. Print total and unit. Expected: 10 kg. Hint: include a new name on the second left-hand side.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tokens and Declarations 04: Infer Go variable types with :=
Check the lesson objective before moving on.
Where can := be used?
After x := 3 in the same block, which line updates x and declares y?