Variables
Variable Declaration
There are several ways to declare variables in Go:
1. Using var keyword
var keywordvar name string // declares variable with zero value ("")
var age int = 25 // declares and initializes
var isActive = true // type inferred from value2. Short Declaration (:=)
:=)name := "John" // type string inferred
age := 25 // type int inferred3. Multiple Declarations
var (
name string
age int
isValid bool
)
// Multiple short declarations
name, age := "John", 25Variable Scope
1. Package Level
package main
var globalVar = "I'm global" // accessible throughout the package
func main() {
// can access globalVar here
}2. Function Level
func main() {
localVar := "I'm local" // only accessible within main()
}3. Block Level
func main() {
if true {
blockVar := "I'm in a block" // only accessible within if block
}
// blockVar is not accessible here
}Zero Values
Go automatically assigns zero values to declared variables:
Numeric types:
0Boolean type:
falseString type:
""Pointer type:
nilReference types (slice, map, channel, interface):
nil
var (
i int // 0
f float64 // 0.0
b bool // false
s string // ""
p *int // nil
)Constants
Constants are declared using the const keyword:
const (
Pi = 3.14159
MaxAge = 120
Greeting = "Hello"
)
// iota for enumerated constants
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)Variable Naming Conventions
CamelCase is the conventional style:
userName(private)UserName(public - exported)
Common Abbreviations:
ifor indexerrfor errorctxfor context
Best Practices
Use Short Variable Names:
For short-lived variables (loops, small functions)
for i := 0; i < 10; i++ { }Use Descriptive Names:
For package-level variables
var ( maxConnections = 100 defaultTimeout = time.Second * 30 )Group Related Variables:
var ( firstName, lastName string age int )Avoid Redundant Names:
// Good var count int // Bad var countNumber int
Common Patterns
1. Error Checking
if err := doSomething(); err != nil {
return err
}2. Multiple Return Values
name, age, err := getPerson()
if err != nil {
return err
}3. Blank Identifier
// Ignore second return value
name, _ := getPerson()Variable Type Conversion
var i int = 42
var f float64 = float64(i)
var s string = strconv.Itoa(i) // Convert int to stringTips and Tricks
Use
:=when possible:Shorter and cleaner than
varBut remember it can't be used at package level
Declare variables close to use:
Keeps code readable
Makes scope clear
Group related declarations:
Improves readability
Shows relationships between variables
Use meaningful names:
Variables should be descriptive
Length of name should match scope size
Additional Resources
Last updated
Was this helpful?