Go Variables:
Variables are fundamental building blocks in Go programming that allow you to store and manipulate data. Here's a comprehensive explanation of variables in Go:
Variable Declaration Basics
In Go, you can declare variables in several ways:
1. Explicit Declaration with var
go
var name type = expressionExample:
go
var age int = 30
var name string = "Alice"
var isActive bool = true2. Type Inference (Type can be omitted if initialized)
go
var name = expressionExample:
go
var age = 30
var name = "Alice"
var isActive = true3. Short Variable Declaration (Inside functions only)
go
name := expressionExample:
go
age := 30
name := "Alice"
isActive := trueZero Values
In Go, variables declared without explicit initialization are given their zero value:
- Numeric types:
0 - Boolean:
false - Strings:
""(empty string) - Pointers, functions, interfaces, slices, channels, maps:
nil
Example:
go
var i int
var f float64
var b bool
var s stringMultiple Variable Declaration
You can declare multiple variables at once:
go
var a, b, c int
var x, y, z = 1, 2.5, "foo"
i, j := 0, 1
var (
name = "Alice"
age = 30
employed bool
)Variable Scope
- Package-level variables: Declared outside any function, visible throughout the package
- Local variables: Declared inside functions, visible only within that function
- Block-level variables: Declared within blocks (like if/for), visible only within that block
Constants
Go also supports constants, declared with const:
go
const Pi = 3.14159
const (
StatusOK = 200
StatusNotFound = 404
)Type Conversions
Go requires explicit type conversion:
go
i := 42
f := float64(i)
u := uint(f)Special Variable Types
Blank Identifier
The underscore _ is used to discard values:
go
_, err := someFunction() Pointers
Go supports pointers to access memory addresses:
go
var x int = 1
p := &x
*p = 2 Best Practices
- Use short declarations (:=) inside functions
- Use explicit var declarations at package level
- Group related variable declarations
- Choose meaningful names (prefer userCount over uc)
- Initialize variables when possible rather than relying on zero values
Example Combining Concepts
go
package main
import "fmt"
var (
version string = "1.0.0"
debug bool
)
func main() {
name := "Alice"
age := 30
x, y := 10, 20
var f float64 = float64(x)
ptr := &age
*ptr = 31
fmt.Println("Name:", name, "Age:", age)
fmt.Println("Sum:", x+y)
fmt.Println("Float:", f)
fmt.Println("Version:", version, "Debug:", debug)
}