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 = 25var 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" // stringvar age = 25 // intvar 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 // intvar f = 3.142 // float64var 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 // 0var isSingle bool // falsevar 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