Golang Basics - Variables and Constants
Go is a statically typed language, which means variables must be declared with a type or initialized with a value from which the type can be inferred. Constants are immutable values that are declared using the const
keyword.
π¦ Variables in Go
1. Declaring Variables (Explicit Type)
var name string
name = "Alice"
You declare a variable using the var keyword followed by the name and type.
2. Declaring and Initializing (Explicit Type)
The type is specified, and the variable is initialized in the same line.
var age int = 30
Type Inference (Implicit Type)
Go infers the type (string in this case) from the initial value.
var country = "Mexico"
4. Short Variable Declaration (Inside Functions Only)
This is shorthand for declaring and initializing a variable. You cannot use := outside of functions.
func main(){
city := "Autlan" // OK
}
city := "Autlan" // ERROR
Multiple Variable Declarations
1. Declaring Multiple Variables
var x, y int
x = 1
y = 2
2. Declaring and Initializing Multiple Variables
var a, b, c = 1, "hello", true
3. Using := for Multiple Variables
name, age := "Bob", 25
β οΈ Zero Values
If a variable is declared without an initial value, Go assigns a zero value:
- int β 0
- float64 β 0.0
- string β ββ (empty string)
- bool β false
- pointer or interface β nil
var isActive bool
fmt.Println(isActive) // false
Constants in Go
Constants are declared using the const keyword and must be assigned a value at compile time.
1. Basic Constant Declaration
const Pi = 3.14
2. Typed vs Untyped Constants
const Greeting string = "Hello" // typed
const Language = "Go" // untyped (can adapt to context)
3. Multiple Constants
const (
A = 1
B = 2
C = 3
)
iota β Constant Generator
iota
is a special predeclared identifier in Go, used within constant declarations to simplify the creation of incrementing numbers or patterns.
Each time a const
block is started, iota
resets to 0
. Then it increments by 1 with each new line within that block.
const (
First = iota // 0
Second // 1
Third // 2
)
You can explicitly write iota or let Go repeat the expression from the previous line.
You can also do bit shifting or expressions with iota:
const (
_ = iota // skip zero
KB = 1 << (10 * iota) // 1 << 10
MB = 1 << (10 * iota) // 1 << 20
GB = 1 << (10 * iota) // 1 << 30
)
- iota is reset to 0 in every new const block.
- It increments by 1 on each line.
- Great for enums, sequences, flags, and bit shifts.
- Can be combined with expressions for more power.
β Best Practices
- Use := for short variable declarations inside functions.
- Use var when declaring at the package level or when zero value initialization is needed.
- Prefer constants over variables when the value should never change.
- Name constants with all uppercase letters or use PascalCase depending on style guides.