Theory
What a function is
Last lesson we made a promise: we stop repeating the printing. The tool is a function: a named piece of code you write once and call as many times as you like.
func formatItem(title string, pages int, read bool) string {
return fmt.Sprintf("Book: %s | pages: %d | read: %v", title, pages, read)
}
Anatomy:
func+ a name — like a variable, but it stores an action instead of a value.- Parameters in the parentheses — the inputs, with types:
title string, pages int, read bool. - Return type after the parentheses — what comes out: here a
string. return— hands the result back to the caller.
You call it like this: line := formatItem("Dune", 412, true) — the parameters fill from the arguments in the same order.
Scope: parameters and variables created inside live only between the function's { }. Once the function ends they are gone — which is why two functions can happily use the same variable name.
The course rule from today on: main does almost nothing itself — it only calls functions. The logic lives in functions with clear names.