A variable gives a value a name. Its type defines the values it can hold and the operations allowed on it. Control flow determines which instructions run and how often. In this lesson, you will combine these ideas to process a small batch of work and explain the result without relying on hidden conversions.
Create a fresh module as described in lesson 1. Save the complete example below as main.go. All its imports come from Go's standard library.
Declare values deliberately
var count int declares an integer without an explicit initial value. It starts at its zero value, which is 0. The zero value is false for bool and the empty string for string. Variables do not begin with arbitrary leftover memory.
Inside a function, count := 3 declares a variable and infers its type. Later assignments use count = 4. A short declaration must introduce at least one new variable in the current scope. At package level, use var or const, not :=. A constant, such as const batchLimit = 5, represents a value that cannot be reassigned.
Common choices are int for counts and indices, int64 when a fixed signed width is needed, float64 for approximate floating-point calculations, bool for conditions, and string for text. byte is an alias for uint8; rune is an alias for int32, conventionally used for Unicode code points. The Tour's type introduction shows these basic types.
Run a batch calculation
package main
import (
"fmt"
"strconv"
)
func main() {
var ready bool
var completed int
var note string
fmt.Printf("defaults: %t %d %q\n", ready, completed, note)
requested, err := strconv.Atoi("7")
if err != nil {
fmt.Println("invalid item count")
return
}
const batchLimit = 5
accepted := requested
if accepted > batchLimit {
accepted = batchLimit
}
total := 0
for item := 1; item <= accepted; item++ {
if item == 3 {
continue
}
total += item
completed++
}
status := ""
switch {
case completed == 0:
status = "empty"
case completed < accepted:
status = "partial"
default:
status = "complete"
}
fmt.Printf("%s: %d items, total %d\n", status, completed, total)
fmt.Println("division:", 5/2, float64(5)/2)
}
Run go run .. Expected output:
defaults: false 0 ""
partial: 4 items, total 12
division: 2 2.5
The request starts at seven, but the accepted batch is capped at five. The loop visits one through five; continue skips three. Four items contribute 1 + 2 + 4 + 5, giving twelve. The condition-only switch chooses the first true case. Cases do not fall through automatically, so you rarely need a break after one.
Read conditions and loops
An if condition must be a boolean. An integer is not automatically treated as true or false. Combine conditions with && for “and,” || for “or,” and ! for negation. These operators short-circuit: they skip the second operand when the first already determines the answer.
for handles several repetition styles. The example uses initialization, condition, and update. for remaining > 0 is a condition-only loop; for with no condition repeats until code returns or breaks. break exits the innermost loop or switch. range visits elements in a collection, which you will use in the collections lesson. See the control-flow tour.
Scope is the region where a name is available. A name declared inside an if block stays there. An inner := can also create a new variable with the same name as an outer variable; this is called shadowing. If an update appears to vanish, check whether you changed a new inner variable.
Conversions and pitfalls
Integer division discards the fractional part. Converting after division, as in float64(5 / 2), produces 2, not 2.5. Convert an operand first when a fraction is intended. Numeric types do not mix automatically, and explicit conversions can lose information. Converting a large integer to a narrower type is not input validation.
Text conversion is a separate task. strconv.Atoi parses decimal text into an int and reports invalid or out-of-range input with an error; string(65) represents a Unicode code point and yields "A", not "65". Use strconv.Itoa for an integer's decimal spelling. Consult the strconv reference when choosing a conversion.
Exercise: classify valid scores
Parse a score from text. Reject values outside zero through one hundred. Print pass for at least fifty and retry otherwise. Try "75", "49", "101", and "oops" by editing the input between runs.
Solution guidance
First check the parsing error and return on failure. Next check score < 0 || score > 100 and return on an invalid range. Only then decide between score >= 50 and the remaining valid scores. This order prevents an invalid score such as 101 from being reported as a pass. Expected outcomes are pass, retry, a range error, and a parse error respectively.
Previous: Modules and Packages. Next: Functions and Defer.

