variables-constantes-inferencia-go

Variables and constants in Go with type inference

  • 5 min

A variable in Go is a name associated with a value of a specific type. A constant represents a value that can be determined at compile time and does not change during execution.

In the previous article, we saw the basic structure of a program. Today we’re going to get down to the nitty-gritty and talk about the building blocks of software: variables and constants.

Go is a statically typed language. This means that, unlike JavaScript or Python, once you define that a box contains shoes (an int), you cannot later try to put a scarf (a string) inside. The compiler will complain and won’t generate the executable.

However, we don’t always have to write the type. That’s where type inference and short declaration with := come in.

When to use each declaration

SituationSyntaxExample
Inside a function (95% of cases)Short operator :=total := 10
Inside a function (we want Zero Value)Explicit varvar total int
Outside a function (Package level)var or var Blockvar Version = "1.0"
Immutable valuesconstconst Pi = 3.14

Standard declaration with var

The most explicit and “classic” way to declare a variable in Go is using the var keyword.

The syntax is: var variableName type.

package main

import "fmt"

func main() {
    var age int = 35
    var name string = "Luis"

    fmt.Println(name, "is", age, "years old")
}
Copied!

Notice something interesting: the type goes last. In C#, we would say int age. In Go, we say var age int. This is done to improve readability when declarations become complex (like function pointers).

Type inference

Go is smart. If you initialize the variable with a value, the compiler already knows its type. You don’t need to write it explicitly.

var age = 35       // Go deduces it's int
var price = 10.5   // Go deduces it's float64
var active = true  // Go deduces it's bool
Copied!

Although inference is convenient, using explicit var is useful when you want a specific type different from the default (e.g., uint8 instead of int).

The short declaration :=

Inside a function, Go allows omitting the var keyword and the type using the short assignment operator :=.

func main() {
    // Declare and initialize in one step
    message := "Hello world"
    counter := 10

    fmt.Println(message, counter)
}
Copied!

This operator does two things at once:

  1. Declares the variable (inferring the type).
  2. Assigns the value.

This is the idiomatic way to work in Go. You’ll see that 90% of variables inside functions are declared this way.

Restrictions of :=

The short operator has two restrictions that often frustrate beginners:

  1. Only works INSIDE functions. You cannot use it at the package level (global variables). There, you must use var.
  2. Must declare at least one new variable. If the variable already exists, you cannot use := again; you must use regular =.
x := 10
x := 20 // ERROR: no new variables on left side of :=
x = 20  // Correct: simple assignment
Copied!

Zero values

In languages like C or C++, if you declare a variable but don’t assign it a value (int a;), that variable contains “garbage” (whatever was at that memory address). This is dangerous. In Java, it forces you to initialize or gives a compilation error.

Go takes a different path: zero values.

Any variable declared without an initial value is automatically initialized to its default zero value.

  • int0
  • float0.0
  • boolfalse
  • string"" (empty string)
  • Pointers, interfaces, functions ➔ nil
var counter int
var message string
var isOn bool

fmt.Printf("Integer: %v, String: %q, Bool: %v\n", counter, message, isOn)
// Output: Integer: 0, String: "", Bool: false
Copied!

Zero values prevent indeterminate data, but they do not make every operation safe. Pointers, maps, slices, channels, functions, and interfaces can have the nil value, and some operations on them cause a panic.

Multiple declarations and blocks

Just like we saw with imports, Go likes to group things. We can declare multiple variables using a var (...) block. This is very common for global or configuration variables.

var (
    courseName = "Go Course"
    duration   = 10
    active     = true
)
Copied!

We can also declare multiple variables on a single line (parallelism):

x, y := 10, 20
firstName, lastName := "Luis", "Llamas"
Copied!

This is key because Go allows functions to return multiple values, and we’ll capture them this way.

Constants

Constants are declared with const. They are values that cannot change during program execution.

const Pi = 3.14159
const BaseURL = "https://luisllamas.es"
Copied!

Characteristics of constants in Go

Constants in Go are a bit special compared to other languages:

  1. They must be computable at compile time. You cannot assign the result of a function like math.Sqrt(4) to a constant, because that happens when the program runs.
  2. They have flexible types. A numeric constant “without a type” can act as int or float depending on where you use it, until a context is forced.
const max = 100 // Constant without explicit type

func main() {
    var integer int = max * 10      // Works, max acts as int
    var floating float64 = max * 0.5 // Works, max acts as float
}
Copied!