Go Variables
Go - Variables
Section titled “Go - Variables”A variable is a named storage location in memory that holds a value. Programs use variables to store and manipulate data.
Every variable in Go has a specific type, which dictates:
Variable names (identifiers) follow the rules outlined in the Basic Syntax chapter (start with letter or underscore, followed by letters, digits, underscores; case-sensitive).
Common Basic Variable Types
Section titled “Common Basic Variable Types”Go offers a rich set of built-in types. Here are some fundamental ones:
| Type | Description | Example Values |
|---|---|---|
| bool | Boolean value | true, false |
| string | Sequence of bytes (often representing UTF-8 encoded text) | "Hello, Go!", "" |
| int | Signed integer (size depends on the platform: 32 or 64 bits) | -10, 0, 123 |
| int8, int16, int32, int64 | Signed integers with specific bit sizes | -128 to 127 (int8), etc. |
| uint | Unsigned integer (size depends on the platform: 32 or 64 bits) | 0, 42, 1000 |
| uint8, uint16, uint32, uint64 | Unsigned integers with specific bit sizes | 0 to 255 (uint8), etc. |
| byte | Alias for uint8 | 'a', 0x41 |
| rune | Alias for int32. Represents a Unicode code point. | '✓', '世' |
| float32, float64 | Floating-point numbers (IEEE-754 standard). float64 is generally preferred. | 3.14, -0.5, 1.0e6 |
| complex64, complex128 | Complex numbers (real and imaginary parts are float32 or float64) | complex(2, -3) |
Go also provides more complex types like arrays, slices, maps, structs, pointers, channels, interfaces, and functions, which are covered in later chapters.
Declaring Variables
Section titled “Declaring Variables”Declaring a variable tells the compiler to reserve memory for it. Go offers several ways to declare variables:
- Declare with
varand type (Zero Value):
This form declares one or more variables of a specified type. If no initial value is provided, the variable is initialized to its zero value (e.g., 0 for numeric types, false for bool, "" for string, nil for pointers, slices, maps, etc.).
var count int // Declares an int variable named 'count', initialized to 0var message string // Declares a string variable 'message', initialized to ""var isActive bool // Declares a bool variable 'isActive', initialized to false
var i, j, k int // Declares multiple int variables, all initialized to 0- Declare with
var, type, and initial value:
This form declares a variable and explicitly assigns an initial value.
var score int = 100var name string = "Alice"var pi float64 = 3.14159- Declare with
varand initial value (Type Inference):
If you provide an initial value, Go can often infer the type, so you can omit the type specification.
var age = 30 // Type inferred as intvar greeting = "Hi there" // Type inferred as stringvar enabled = true // Type inferred as bool
// Declare multiple variables with inferred typesvar a, b, c = 1, 2.5, "xyz"- Short Variable Declaration (
:=) (Type Inference):
Inside functions, you can use the := short assignment statement. This declares the variable(s) and initializes them using type inference. This is the most common way to declare variables within functions in Go.
Note: Short variable declarations (:=) can only be used inside functions, not at the package level. At the package level, you must use var.
func main() { count := 10 // Type inferred as int message := "Success" // Type inferred as string isValid := false // Type inferred as bool
x, y := 5, "five" // Declare multiple variables}When to use var vs :=:
Example: Declaration Styles
Section titled “Example: Declaration Styles”package main
import "fmt"
// Package-level variable (must use var)var globalMessage = "This is global"
func main() { // Using var with zero value var counter int fmt.Printf("Initial counter: %d (Type: %T)\n", counter, counter)
// Using var with explicit type and value var price float64 = 99.95 fmt.Printf("Price: %.2f (Type: %T)\n", price, price)
// Using var with type inference var quantity = 5 fmt.Printf("Quantity: %d (Type: %T)\n", quantity, quantity)
// Using short variable declaration (:=) productName := "Widget" fmt.Printf("Product: %s (Type: %T)\n", productName, productName)
// Mixed declaration with type inference a, b, c := true, 10.5, "Mixed" fmt.Printf("a: %t (%T), b: %.1f (%T), c: %s (%T)\n", a, a, b, b, c, c)
fmt.Println(globalMessage)}When compiled and executed, this produces:
Initial counter: 0 (Type: int)Price: 99.95 (Type: float64)Quantity: 5 (Type: int)Product: Widget (Type: string)a: true (bool), b: 10.5 (float64), c: Mixed (string)This is globalAssignability (Lvalues and Rvalues)
Section titled “Assignability (Lvalues and Rvalues)”In assignment operations (=, :=), the left side must refer to a memory location where a value can be stored (sometimes called an lvalue or, more simply, an assignable operand). The right side must produce a value (sometimes called an rvalue).
Variables are assignable:
count = 10 // Valid: 'count' refers to a memory locationLiterals (like numbers or strings) are values, not memory locations, so they cannot be on the left side of an assignment:
100 = count // Invalid: Cannot assign to the literal value 100