mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Variables

Declaration

Variables in Go are declared using the var keyword.

The basic syntax for declaring a variable:

go
// `name` is the name of the variable.
// `type` is the type of the variable's value.
var name type

Examples:

go
// Variable declarations with initial values.
var name string = "John"
var age int = 25
var isSingle bool = true

It’s possible to declare multiple variables with the same type in a single statement:

go
var firstName, lastName string = "John", "Doe"

var a, b, c int = 1, 2, 3

Variable declarations may be factored into blocks:

go
var (
  name     string = "John"
  age      int    = 20
  isSingle bool   = true
)

Type Inference

The type can be omitted if an initialzer is present:

go
// The variable's type is inferred from the value on the right hand side.
var name = "John"   // string
var age = 25        // int
var isSingle = true // bool

// Multiple variables can be delcared and initialized in 1 statement.
var a, b, c = 20, "John", true // int, string, bool

// When not using an explicit type with numeric constants
// the inferred type will depend on the precision of the constant.
var i = 42           // int
var f = 3.142        // float64
var g = 0.867 + 0.5i // complex128

Zero Value

If a variable is declared without an initial value, the variable will be initialized to its zero value (a default value for each type):

go
var name string   // "" (empty string)
var age int       // 0
var isSingle bool // false
var a, b, c int   // 0, 0, 0

Constants

Constants are declared like variables but with the const keyword:

go
const Pi = 3.14 // Cannot be reassigned