0
0
GoHow-ToBeginner · 3 min read

How to Declare Variables in Go: Syntax and Examples

In Go, you declare a variable using the var keyword followed by the variable name and type, like var x int. You can also use the short declaration form x := 10 which infers the type automatically.
📐

Syntax

There are two main ways to declare variables in Go:

  • Using var keyword: Declare the variable name and type explicitly.
  • Short declaration :=: Declare and initialize a variable with type inferred automatically.

Example syntax:

var name type
name := value
go
package main

import "fmt"

func main() {
    var age int       // Declare variable 'age' of type int
    age = 30         // Assign value to 'age'

    name := "Alice" // Declare and initialize 'name' with type inferred

    fmt.Println(age)
    fmt.Println(name)
}
Output
30 Alice
💻

Example

This example shows declaring variables with and without explicit types, assigning values, and printing them.

go
package main

import "fmt"

func main() {
    var count int = 5          // Declare with type and initial value
    var price = 9.99           // Type inferred from value
    message := "Hello Go!"    // Short declaration with inferred type

    fmt.Println(count)
    fmt.Println(price)
    fmt.Println(message)
}
Output
5 9.99 Hello Go!
⚠️

Common Pitfalls

Common mistakes when declaring variables in Go include:

  • Using := outside functions (only allowed inside functions).
  • Declaring a variable without initializing it and then trying to use it before assignment.
  • Shadowing variables unintentionally by redeclaring them in inner scopes.

Example of wrong and right usage:

go
package main

import "fmt"

func main() {
    // Wrong: short declaration outside function (uncommenting causes error)
    // x := 10

    var x int
    x = 10 // Correct: declare then assign

    if true {
        x := 20 // Shadows outer x, different variable
        fmt.Println(x) // Prints 20
    }
    fmt.Println(x) // Prints 10
}
Output
20 10

Key Takeaways

Use var to declare variables with explicit types or initial values.
Use := for short variable declaration inside functions with type inference.
Short declaration := is not allowed outside functions.
Be careful of variable shadowing in nested scopes.
Variables declared without initialization get zero values of their type.