Variables & Types
Variables are the foundation of any programming language. In this lesson, you'll learn how to declare variables in Go, understand Go's type system, and master type inference and conversions.
Figure: Complete Go Variables & Types Hierarchy - Declarations, Basic Types, Composite Types, Reference Types, and Conversions
Variable Declaration with var
Go provides the var keyword for declaring variables. The syntax is:
var name type = value
Let's see it in action:
Click Run to execute your code
vardeclares a variable- Type comes after the variable name (unlike C/Java)
- You can initialize the variable immediately
- Variables without initialization get their "zero value"
Zero Values
In Go, variables declared without an explicit initial value are given their zero value:
| Type | Zero Value | Example |
|---|---|---|
Numeric types (int, float64) |
0 |
var count int â 0 |
Boolean (bool) |
false |
var active bool â false |
String (string) |
"" (empty string) |
var name string â "" |
| Pointers, slices, maps, channels, functions, interfaces | nil |
var ptr *int â nil |
Short Variable Declaration (:=)
Go provides a shorthand syntax using := for declaring and
initializing variables
inside functions:
Click Run to execute your code
- Can only be used inside functions
- Type is inferred from the value
- More concise than
var - Most common way to declare variables in Go
var vs := When to Use Which?
Use var |
Use := |
|---|---|
| Package-level variables | Local variables in functions |
| When you need to specify the type explicitly | When type can be inferred |
| When declaring without initialization | When initializing immediately |
var count int |
count := 0 |
Go's Type System
Go is a statically typed language, meaning variable types are known at compile time. Here are the basic types:
Click Run to execute your code
Numeric Types
| Type | Size | Range/Description |
|---|---|---|
int |
32 or 64 bits | Platform dependent (most common) |
int8 |
8 bits | -128 to 127 |
int16 |
16 bits | -32,768 to 32,767 |
int32 |
32 bits | -2 billion to 2 billion |
int64 |
64 bits | Very large numbers |
uint, uint8, uint16, etc.
|
Varies | Unsigned (positive only) |
float32 |
32 bits | Single precision |
float64 |
64 bits | Double precision (default for decimals) |
Other Basic Types
bool- Boolean values (trueorfalse)string- UTF-8 encoded textbyte- Alias foruint8rune- Alias forint32, represents a Unicode code point
Type Inference
Go can automatically infer the type of a variable from its initial value:
// Type is inferred
message := "Hello" // string
count := 42 // int
pi := 3.14159 // float64
isActive := true // bool
// You can check the type using %T in Printf
fmt.Printf("Type of message: %T\n", message) // string
fmt.Printf("Type of count: %T\n", count) // int
fmt.Printf("Type of pi: %T\n", pi) // float64
- Integers default to
int - Floating-point numbers default to
float64
Type Conversion
Unlike some languages, Go requires explicit type conversion. There are no automatic conversions:
Click Run to execute your code
Type(value),
not
(Type)value like in C/Java. For example: float64(x),
not
(float64)x.
Common Mistakes
1. Using := outside functions
// â Wrong - syntax error
package main
count := 0 // Can't use := at package level
func main() {
// ...
}
// â
Correct
package main
var count = 0 // Use var at package level
func main() {
// ...
}
2. Redeclaring variables with :=
// â Wrong - redeclaration
func main() {
name := "Alice"
name := "Bob" // Error: no new variables on left side
}
// â
Correct - use = for reassignment
func main() {
name := "Alice"
name = "Bob" // Reassignment, not declaration
}
3. Mixing types without conversion
// â Wrong - type mismatch
var x int = 10
var y float64 = 3.14
result := x + y // Error: mismatched types
// â
Correct - explicit conversion
var x int = 10
var y float64 = 3.14
result := float64(x) + y // Works!
4. Unused variables
// â Wrong - declared but not used
func main() {
name := "Alice" // Error: name declared but not used
fmt.Println("Hello")
}
// â
Correct - use the variable or remove it
func main() {
name := "Alice"
fmt.Println(name) // Now it's used
}
Exercise: Temperature Converter
Task: Create a program that converts temperatures between Celsius and Fahrenheit.
Requirements:
- Declare a variable for Celsius temperature (use 25.0)
- Convert to Fahrenheit using the formula: F = C Ă 9/5 + 32
- Print both temperatures with proper labels
- Use appropriate types (float64)
Show Solution
package main
import "fmt"
func main() {
// Celsius temperature
celsius := 25.0
// Convert to Fahrenheit
fahrenheit := celsius * 9/5 + 32
// Print results
fmt.Printf("%.1f°C = %.1f°F\n", celsius, fahrenheit)
// Bonus: Convert back to verify
celsiusCheck := (fahrenheit - 32) * 5/9
fmt.Printf("%.1f°F = %.1f°C\n", fahrenheit, celsiusCheck)
// Type information
fmt.Printf("\nType of celsius: %T\n", celsius)
fmt.Printf("Type of fahrenheit: %T\n", fahrenheit)
}
Summary
- var keyword declares variables with explicit types
- := operator provides short declaration with type inference (functions only)
- Zero values ensure variables are always initialized (0, false, "", nil)
- Type comes after the variable name in Go
- Static typing means types are checked at compile time
- Type inference automatically determines types from values
- Explicit conversion required between different types
- Unused variables cause compilation errors
What's Next?
Now that you understand variables and types, you're ready to learn about Constants & Operators. In the next lesson, you'll discover how to define immutable values and perform operations on your data.
Enjoying these tutorials?