Sobes.tech
Junior

What are the differences between quickly declaring a variable and declaring it with the var keyword?

sobes.tech AI

Answer from AI

Short declaration (:=) is only possible inside functions and is a shorthand form of declaration and initialization. The var keyword allows declaring variables of any type, without initialization (they will receive a zero value) or with initialization, as well as at the package level.

Main differences:

Characteristic Short declaration (:=) Declaration via var
Usage location Only inside functions Inside functions and at package level
Initialization requirement Mandatory, the compiler infers the type Not mandatory, variable gets zero value
Multiple declaration Possible for multiple variables Possible for multiple variables
Redeclaration No, if the variable already exists (only assignment) Yes, but only with type specification
Explicit type indication No, the compiler infers Yes, if there is no initialization

Example of short declaration:

// Initialization and declaration of variable user
user := "Alice"

Declaration via var example:

// Declaration of variable age without initialization (will get value 0)
var age int

// Declaration and initialization of variable city
var city string = "New York"

// Declaration of multiple variables
var (
	x, y int = 1, 2
	name string
)