Skip to content

Variables and constants

Go provides several ways to declare variables and constants.

  1. var with typevar name string
  2. var with initializervar name = "Alice" (type inferred)
  3. Short assignment :=name := "Alice" (inside functions only)
  4. Multiple variablesvar x, y int = 1, 2 or x, y := 1, 2
  • Declared with const keyword.
  • Cannot be changed after declaration.
  • Can be untyped (e.g., const Pi = 3.14).

Demonstrate different variable declarations and constants.

package main
import "fmt"
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)
func main() {
var name string = "Alice"
var age = 30
city := "Paris"
var x, y int = 10, 20
a, b := "hello", true
fmt.Println(name, age, city)
fmt.Println(x, y, a, b)
fmt.Println(Pi, StatusOK, StatusNotFound)
}
Terminal window
Alice 30 Paris
10 20 hello true
3.14159 200 404