Short declaration :=
- Go course
- Beginner
- Lesson 14/90
- 4 min
Learn short variable declaration with :=.
Short declaration :=
The short way to declare a variable inside a function in Go is the := operator. Writing x := 5 both creates the variable and infers its type from the right side.
This operator works only inside functions; it cannot be used at package level. var works everywhere, while := is a shortcut for functions.
A variable declared with := can later be reassigned with =. Reusing := with the same name is a compile error unless at least one new variable appears.
The := vs = difference
:= declares a new variable and assigns a value. = assigns to an existing variable. Mixing them up is a common mistake.
For example x := 5 creates x; later x = 10 changes its value. Writing x := 10 again raises a 'no new variables' error.
For functions returning multiple values, a, b := f() is very handy; both variables are declared in one line.
Practice := and =
Create the variable with sayac := 1, then update it twice with =: first sayac = sayac + 1, then sayac = sayac * 10. Print the result.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
sayac := 1
sayac = sayac + 1
sayac = sayac * 10
fmt.Println(sayac)
}Expected output
20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where can the := operator not be used?
- Inside a function
- At package level Correct answer
- Inside a loop
- In an if block
Explanation: := is only for functions, not package level.
2 Short assignment
To assign 5 to x with the short form:
x ____ 5
To assign 5 to x with the short form:
x := 5
Explanation: := is the short variable declaration.
3 Match the operators
| Term | Meaning |
|---|---|
:= |
Short decl |
= |
Assignment |
== |
Equality |
var |
Long decl |