Declaring variables
Go provides several ways to declare variables, each with its own use case:The var keyword
The traditional way to declare variables uses the var keyword:
Explicit type declaration
var- you’re declaring a variablea- the variable’s nameint- the variable’s type= 10- the initial value
Important rule: In Go, if you declare a variable, you must use it. Unused variables cause compilation errors. This prevents dead code and catches typos early.
Type inference
b is automatically typed as int because 10 is an integer.
c becomes a bool because true is a boolean value.
Short declaration syntax
The most common way to declare variables in Go uses the:= operator:
var d = "Go is awesome". It’s concise and idiomatic Go.
When to use each syntax
Here’s a guide for choosing the right declaration style:| Syntax | When to use | Example |
|---|---|---|
var name type = value | When you need to explicitly specify the type | var count int32 = 100 |
var name = value | At package level (outside functions) | var database = "users.db" |
name := value | Inside functions (most common) | message := "Hello" |
Zero values: No undefined errors
One of Go’s safety features is that every variable has a default “zero value” even if you don’t initialize it:Zero values by type:
- Numbers (
int,float64, etc.):0 - Strings:
""(empty string) - Booleans:
false - Pointers, slices, maps, channels, functions, interfaces:
nil
This is a deliberate design decision. Go eliminates entire classes of bugs by ensuring every variable always has a predictable value. No more
undefined is not a function or mysterious null pointer crashes from uninitialized variables.Multiple variable declarations
You can declare multiple variables at once:Multiple with inference
Multiple with short syntax
Grouped declarations
Reassigning variables
Once declared, you can change a variable’s value (but not its type):Variable scope
Variables exist only within their scope (the curly braces{} where they’re declared):
The shadowing trap
Be careful with:= in nested scopes:
Naming conventions
Go has strong conventions for variable names:- Use camelCase:
userName, notuser_name - Short names for short scopes:
ifor loop counters,errfor errors - Descriptive names for longer scopes:
databaseConnection, notdbConn - Exported names start with capital letters:
ExportedVariable
Experiment
Try these exercises:-
Declare your information:
-
Swap two variables (this is a common interview question):
-
Test zero values:
Key takeaways
- Variables store values and give them meaningful names
- Use
varfor explicit declarations,:=for short declarations inside functions - Go infers types automatically when you omit them
- Every variable must be used - unused variables cause compile errors
- All variables have zero values - no undefined errors
:=declares new variables,=reassigns existing ones- Be careful of variable shadowing with
:=in nested scopes