0% completed
Short Variable Declaration Operator(:=) in Go
On This Page
What is ":=" in Go?
Syntax of Short Variable Declaration
Example: Using ":="
Rules for Using ":="
Difference Between "var" and ":="
Limitations of ":="
In Go, the short variable declaration operator (:=) provides a quick way to declare and initialize variables in a single step. It simplifies code by eliminating the need for the var keyword and explicit type definitions.
What is ":=" in Go?
The := operator is a shorthand method for declaring and initializing a variable in the same statement. Unlike var, it does not require specifying the data type because Go automatically infers the type from the assigned value.
Syntax of Short Variable Declaration
variableName := value
variableName→ The name of the variable being declared.:=→ The short declaration operator, which tells Go to create and assign a value in one step.value→ The initial value assigned to the variable. Go will infer the type based on this value.
Example: Using ":="
Explanation of Example
name := "Alice"declares and initializes a variablenamewith a string value.age := 25declares and initializesageas an integer.price := 9.99declarespriceas a floating-point number (float64).- The
fmt.Println()function is used to display the values.
Rules for Using ":="
- Must be used inside a function → The
:=operator is not allowed at the package level. - Requires both declaration and initialization in the same line → You cannot declare a variable and assign a value later.
- At least one new variable must be declared in a multi-variable statement → If multiple variables are assigned using
:=, at least one must be new.
Difference Between "var" and ":="
| Feature | var Declaration | := Declaration |
|---|---|---|
| Explicit type? | Yes (optional) | No (Go infers type) |
| Function scope required? | No | Yes |
| Separate initialization? | Allowed | Not allowed |
| Re-declaration in same scope? | Not allowed | At least one new variable must be declared |
Limitations of ":="
- Cannot be used outside functions →
:=is only allowed inside function bodies and not at the package level. - Cannot be used if the variable is already declared in the same scope, unless a new variable is also declared.
In the next lesson, we will explore Constants in Go, how they differ from variables, and when to use them.
Reading Progress
0%
On This Page
What is ":=" in Go?
Syntax of Short Variable Declaration
Example: Using ":="
Rules for Using ":="
Difference Between "var" and ":="
Limitations of ":="