Variables, Types, and Constants
Declaring variables with `var` and `:=`, Go's basic types, and constants.
What you'll learn
- Declare variables with both `var` and the `:=` short form
- Identify Go's basic types: int, float64, string, bool
- Explain the difference between a variable and a `const`
Explanation
Go is statically typed: every variable has a fixed type, checked at compile time. You can declare one explicitly with var name Type = value, or let Go infer the type from the value using the short declaration name := value -- := can only be used inside a function, never at package level.
Go's basic types include int (platform-sized integer), float64 (double-precision decimal), string, and bool. Unlike some languages, Go does not automatically convert between numeric types -- adding an int and a float64 directly is a compile error; you must convert explicitly with something like float64(someInt).
A const is a compile-time constant -- its value must be knowable at compile time and can never change. Constants are declared with const name = value (no := form exists for constants).
Every declared variable in Go must be used somewhere, just like imports -- an unused local variable is a compile error, not a warning, which is a deliberate design choice to keep code free of dead declarations.
Guided lab
Predict: Variables and type conversion
Read this program and predict exactly what it prints.
package main
import "fmt"
func main() {
name := "Ada"
var age int = 30
const pi = 3.14159
height := 5.5
heightCm := height * 30.48
fmt.Printf("%s is %d years old.\n", name, age)
fmt.Printf("Height in cm: %.1f\n", heightCm)
fmt.Println("Pi is approximately", pi)
}Stuck? Get a hint.
Common mistakes
- Trying to use `:=` at package level (outside any function) -- it only works for local variables inside a function body.
- Adding an `int` and a `float64` directly without an explicit conversion, expecting automatic promotion like in some other languages.
- Declaring a local variable and never using it, forgetting Go treats this as a compile error.
Knowledge check
Takeaway
Use `:=` for local variables when the type is obvious from the value, `var` when you need an explicit type or are at package level, and remember Go never auto-converts between numeric types.
Summary
Go variables are statically typed, declared with `var` or `:=`; constants use `const`; unused local variables and cross-type arithmetic without conversion are both compile errors.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.