Declaring Variables
Using the var keyword
var varName type = valueVariables declared without an explicit initial value receive their zero value.
-
Either
type,value, or both must be specified:var name string = "John" // explicit type and value var surname = "Doe" // type inferred as string var age int16 // explicit type, zero value (0) -
Multiple variables in a single line, same or different types:
var name, age = "John", 30 // mixed types, inferred var a, b, c int = 1, 2, 3 // all must match the declared type var x, y int // both zero value (0) -
Grouped declaration:
var ( name string = "John" surname = "Doe" // inferred as string age int // zero value (0) )
Using the := syntax
varName := value-
Multiple variables in a single line:
name, age := "John", 30Re-declaration of a variable in the same scope is not allowed.
BUT
If at least one identifier on the left side is new, this syntax is allowed.
x := 10 x := 20 // <-- compiler: no new variables on left side of := x, y := 20, 30 // y is new, so this is allowed fmt.Println(x, y) // 20 30New identifiers are declared and existing ones are reassigned.
Using the const keyword
Constants are fixed values that cannot change after declaration.
const varName type = valueConstants must be known at compile time. They cannot depend on variables, function calls, or any other runtime values. Expressions that the compiler can evaluate during compilation are allowed. Constants are limited to booleans, numbers, and strings.
-
Constants declaration may omit the type but must include a value:
const daysInWeek int = 7 // explicit type and value const hoursInDay = 24 // type is inferred as int -
Grouped declaration:
const ( daysInWeek = 7 hoursInDay = 24 )