Grokking Go
Vote

0% completed

​

Short Variable Declaration Operator(:=) in Go

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.
Image

Example: Using ":="

Go
Go

. . . .

Explanation of Example

  • name := "Alice" declares and initializes a variable name with a string value.
  • age := 25 declares and initializes age as an integer.
  • price := 9.99 declares price as 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 ":="

Featurevar Declaration:= Declaration
Explicit type?Yes (optional)No (Go infers type)
Function scope required?NoYes
Separate initialization?AllowedNot allowed
Re-declaration in same scope?Not allowedAt 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%


Vote for new content

On This Page

What is ":=" in Go?

Syntax of Short Variable Declaration

Example: Using ":="

Rules for Using ":="

Difference Between "var" and ":="

Limitations of ":="