Short Variable Declaration
Start with Short Variable Declaration
Go uses := to declare and initialize local variables concisely. This syntax is very common inside functions.
What you’ll learn
- Use := inside functions.
- Explain how Go infers a type.
- Recognize the “at least one new variable” rule.
Understand the idea
count := 3 declares count and infers its type from 3. It is a declaration, not an ordinary assignment, and cannot be used for package-level variables.
In the same scope, a short declaration with multiple names is valid only when at least one non-blank name is new. For example, count, label := 4, "items" updates the existing count and introduces label.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
count := 3
count, label := 4, "items"
fmt.Println(count, label)
count = 5
fmt.Println("Now:", count)
}
Output
4 items
Now: 5Trace what the program does
First count is introduced. The second short declaration has a new name, label, so it is legal and updates count. Finally ordinary assignment changes count to 5.
Avoid common mistakes
- Writing
count := 5again in the same block with no new variable is an error. - Short declarations cannot be written directly at package scope.
Try it yourself
Change count, label := 4, "items" to count, unit := 4, "books" and update the print call. Explain why the second declaration is legal.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Short Variable Declaration in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.