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
2. Function Level
3. Block Level
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
Constants
Constants are declared using the const keyword:
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)
Use Descriptive Names:
For package-level variables
Group Related Variables:
Avoid Redundant Names:
Common Patterns
1. Error Checking
2. Multiple Return Values
3. Blank Identifier
Variable Type Conversion
Tips 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?