Stage 1 · Code
Variables, Types & Control Flow
Declaring Variables
Understand every way Go lets you name and store values — and know which form to reach for in each situation.
What is a Variable?
A variable is a named storage location. When your program runs, every variable holds a value of a specific type. You can read the value, replace it, and use it in expressions.
In Go, you cannot use a variable before declaring it and you cannot leave a declared variable unused inside a function. Both rules are enforced by the compiler, not just convention.
Every variable has a type that is known at compile time. You can store a string in a string variable but never an integer, and Go catches that mistake before your program ever runs.
var Declarations
The var keyword is the explicit declaration form. You can provide a type, an initial value, or both. When you supply only a type, Go initializes the variable to its zero value — a safe default for that type.
Short Declarations with :=
Inside a function, := declares and assigns in one step. Go infers the type from the value on the right. Most Go code inside functions uses := because it is concise without hiding information.
| Form | Where allowed | Type required? | Best for |
|---|---|---|---|
| var x int | Anywhere | Yes (explicit) | Declaring with zero value or clear type |
| var x = value | Anywhere | No (inferred) | Package-level with clear initial value |
| x := value | Functions only | No (inferred) | Most local declarations |
Idiomatic Go uses := for local variables unless you specifically want the zero value (in which case var x int is clearest) or need to group related declarations in a var block.
Scope and Shadowing
Scope is the region of code where a name is visible. In Go, every set of curly braces {} creates a new scope. A variable declared inside a block disappears when that block ends.
If you use := when you meant =, you create a new variable that shadows the outer one. The outer variable keeps its old value even though you thought you changed it.
Naming Conventions
Go variable names use camelCase: start with a lowercase letter and capitalize each subsequent word. Keep names short when the scope is small and longer when the purpose is not obvious from context.
- Use camelCase:
userName,maxRetries,httpClient. - Single-letter names (
i,n,v) are fine in short loops and small functions. - Longer, descriptive names (
serverAddress,requestTimeout) for package-level or exported identifiers. - Avoid underscores in names (except the blank identifier
_). - Acronyms are all-caps or all-lowercase:
httpURL,userID, nothttpUrloruserId.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.