Go basics: types, functions and defer

The parts of Go you need before writing a limiter: variables and types, constants, control flow, functions with multiple return values, and defer.

Learning outcomes

  • Declare variables with var and :=, and pick between int, float64, string, bool and time.Duration.
  • Write functions that return several values, including a result and an error.
  • Use if, for and switch the Go way, including for as the only loop.
  • Use defer to run cleanup when a function returns, and say in what order deferred calls run.
  • Format and run a small program with go run.
Prerequisite conceptsGo packages

What you will learn

Go is deliberately small as a language. It gives you a limited set of control-flow constructs, explicit types, straightforward functions, and a few rules that make programs easier to read.

This lesson covers the language features you need to write your first backend code. The examples use rate-limiter terminology because that is what you will build throughout Week 1.

By the end, you should be able to:

  • Declare variables and constants, and understand Go's zero values.
  • Choose appropriate types for numbers, text, booleans, and durations.
  • Write functions that accept parameters and return one or more values.
  • Use if, for, range, and switch.
  • Understand scope, shadowing, and short declarations.
  • Use defer for cleanup and understand its execution order.
  • Store functions in variables and pass them to other functions.
  • Format, run, and inspect a small Go program.

Variables, constants, and zero values

A variable is a named location that holds a value. Go requires every variable to have a type, either explicitly declared or inferred from its initial value.

There are three common ways to declare a variable.

Using var

Use var when you want to declare a variable explicitly or initialize it later.

go
var limit int
var serviceName string = "rate-limiter"
var enabled bool = true

The first declaration does not provide an initial value. Go assigns the type's zero value automatically.

TypeZero value
int0
float640
string""
boolfalse

Zero values are useful because variables always start in a predictable state. You do not need to initialize every variable manually.

go
package main

import "fmt"

func main() {
    var requestCount int
    var serviceName string
    var enabled bool

    fmt.Println(requestCount)
    fmt.Println(serviceName)
    fmt.Println(enabled)
}

Output:

0

false

Using :=

Inside a function, the short declaration operator := declares a variable and infers its type from the assigned value.

go
func main() {
    limit := 100
    serviceName := "rate-limiter"
    enabled := true
}

Go infers limit as int, serviceName as string, and enabled as bool.

You cannot use := outside a function. At package level, use var or const.

A common mistake is using := when you intend to update an existing variable.

go
func main() {
    limit := 100
    limit = 200
}

The first line declares limit. The second assigns a new value to the existing variable. Use = for assignment, not :=.

Using const

A constant is a value that cannot be changed after compilation.

go
const defaultLimit = 100
const serviceName = "rate-limiter"
const secondsPerMinute = 60

Constants are appropriate for fixed configuration values, mathematical values, and strings that should not change while the program runs.

Go does not allow a constant to be declared without an initial value.

Choosing types

Go has a relatively small set of built-in types. Choosing the right one makes your code clearer and helps the compiler catch mistakes.

Integers and floating-point numbers

Use int for ordinary whole numbers, such as request counts, limits, and loop indexes.

go
var requestCount int = 42
var limit int = 100

Go also provides fixed-width integer types such as int32, int64, uint32, and uint64. You do not need to choose these for every ordinary calculation. Use them when a specific width or unsigned range is part of an API or data format.

Use float64 for numbers that need fractional values.

go
var averageRequests float64 = 42.5

Be careful with integer division. When both operands are integers, Go produces an integer result and discards the fractional part.

go
package main

import "fmt"

func main() {
    fmt.Println(5 / 2)
    fmt.Println(5.0 / 2.0)
}

Output:

2
2.5

If you need a fractional result from integer values, convert at least one operand to a floating-point type.

go
requests := 5
workers := 2

average := float64(requests) / float64(workers)
fmt.Println(average)

Strings, bytes, and runes

A string represents text. Go strings are immutable sequences of bytes, usually containing UTF-8 encoded text.

go
service := "rate-limiter"
message := "request accepted"

You can combine strings with +:

go
service := "rate-limiter"
message := "starting " + service

Useful string operations are available in the standard library's strings package.

go
package main

import (
    "fmt"
    "strings"
)

func main() {
    key := "  user-42  "

    normalized := strings.TrimSpace(key)
    fmt.Println(normalized)
    fmt.Println(strings.Contains(normalized, "user"))
    fmt.Println(strings.HasPrefix(normalized, "user-"))
}

A byte is an alias for uint8. It represents one byte and is useful when working with raw encoded data.

A rune represents a Unicode code point. It is useful when you need to work with individual text characters rather than the underlying UTF-8 bytes.

go
package main

import "fmt"

func main() {
    text := "Go"
    firstByte := text[0]

    character := 'G'
    fmt.Println(firstByte)
    fmt.Println(character)
}

A single-quoted character literal such as 'G' has type rune unless its type is otherwise inferred or converted.

Do not assume that indexing a string gives you a complete Unicode character. It gives you one byte. For text that may contain non-ASCII characters, use rune-aware operations.

Booleans

A bool holds either true or false. It is commonly used for conditions and decisions.

go
enabled := true
withinLimit := false

Go does not implicitly convert integers or strings to booleans. A condition must evaluate to a boolean.

Durations

Time-related code often needs a value representing a duration, such as a timeout or the length of a rate-limit window.

Go's time.Duration is a named type based on an integer representation. It expresses a duration in nanoseconds, but the standard library provides readable constants such as time.Second and time.Minute.

go
package main

import (
    "fmt"
    "time"
)

func main() {
    window := 30 * time.Second
    timeout := 2 * time.Minute

    fmt.Println(window)
    fmt.Println(timeout)
}

Using duration constants is clearer than writing raw nanosecond values. You will use durations when working with rate-limit windows and injected clocks later in the week.

Functions: reusable units of work

A function is a named unit of code that can receive input, perform work, and return results. Functions help separate a program into small operations with clear responsibilities.

The general form is:

go
func functionName(parameterName parameterType) returnType {
    return value
}

For example, a rate limiter needs to decide whether a request count is within a configured limit.

go
package main

import "fmt"

func withinLimit(requestCount int, limit int) bool {
    return requestCount <= limit
}

func main() {
    allowed := withinLimit(42, 100)
    fmt.Println(allowed)
}

The function accepts two int parameters and returns a bool.

When multiple parameters have the same type, you can write the type once at the end of the parameter list.

go
func withinLimit(requestCount, limit int) bool {
    return requestCount <= limit
}

This is equivalent to the earlier declaration.

Multiple return values

Go functions can return more than one value. This is particularly important because Go commonly returns an error alongside the result of an operation.

go
func remainingRequests(requestCount, limit int) (int, error) {
    if requestCount < 0 {
        return 0, fmt.Errorf("request count cannot be negative")
    }

    if limit < 0 {
        return 0, fmt.Errorf("limit cannot be negative")
    }

    return limit - requestCount, nil
}

The return type is (int, error). The first value is the result, and the second reports whether the operation failed.

An error is a built-in interface type used by Go to represent an error condition. You will study interfaces and errors in a later lesson. For now, understand that nil means there is no error.

The caller must handle both returned values.

go
package main

import (
    "fmt"
)

func remainingRequests(requestCount, limit int) (int, error) {
    if requestCount < 0 {
        return 0, fmt.Errorf("request count cannot be negative")
    }

    if limit < 0 {
        return 0, fmt.Errorf("limit cannot be negative")
    }

    return limit - requestCount, nil
}

func main() {
    remaining, err := remainingRequests(42, 100)
    if err != nil {
        fmt.Println("cannot calculate:", err)
        return
    }

    fmt.Println("remaining requests:", remaining)
}

The caller checks the error before using the result. This is the normal Go pattern for operations that can fail.

A useful mental model is that the function hands two independent values back to its caller. The caller decides what to do with the result and whether to continue after an error.

Show a function receiving a request count and limit, returning a result and an error together, and the caller checking the error before using the result.Show a function receiving a request count and limit, returning a result and an error together, and the caller checking the error before using the result.

Named return values

Go also allows return values to be named in the function signature.

go
func remainingRequests(requestCount, limit int) (remaining int, err error) {
    if requestCount < 0 {
        err = fmt.Errorf("request count cannot be negative")
        return
    }

    remaining = limit - requestCount
    return
}

The names remaining and err behave like variables declared at the beginning of the function. A bare return returns their current values.

This is called a naked return. It can be useful for short functions, but it can also make code harder to understand because the returned values are not visible at the return statement.

Prefer explicit return values in most ordinary functions:

go
return limit - requestCount, nil

That makes the function's behavior easier to review.

Variadic parameters

A variadic parameter allows a function to accept zero or more values of the same type. The parameter is written with ... before its type.

go
func totalRequests(counts ...int) int {
    total := 0

    for _, count := range counts {
        total += count
    }

    return total
}

You can call it with different numbers of arguments:

go
totalRequests()
totalRequests(10)
totalRequests(10, 20, 30)

Inside the function, counts behaves like a slice. You will learn slices in the next lesson. For now, you only need to know that the function can iterate over the supplied values.

Anonymous functions and closures

A function does not always need a name. An anonymous function is a function expression that can be assigned to a variable or passed directly to another function.

go
package main

import "fmt"

func main() {
    isAllowed := func(requestCount, limit int) bool {
        return requestCount <= limit
    }

    fmt.Println(isAllowed(42, 100))
}

The variable isAllowed holds a function value. You call it using the same syntax as a named function.

A function can also capture variables from the surrounding scope. Such a function is called a closure.

go
package main

import "fmt"

func main() {
    limit := 100

    isAllowed := func(requestCount int) bool {
        return requestCount <= limit
    }

    fmt.Println(isAllowed(42))
    fmt.Println(isAllowed(120))
}

The anonymous function uses limit even though limit is not one of its parameters. It captures the variable from the surrounding function.

This ability to store and pass functions is important for the rate limiter. Later, you will provide a clock function to a component so that tests can control what time it sees. The clock can be stored as a function value rather than hard-coded into the component.

Control flow: deciding what runs

Control flow determines which statements execute and how often they execute. Go keeps this deliberately simple: it has if, switch, and one looping construct, for.

if and else

Use if to execute code only when a condition is true.

go
func isAllowed(requestCount, limit int) bool {
    if requestCount <= limit {
        return true
    }

    return false
}

An else branch handles the opposite case.

go
func status(requestCount, limit int) string {
    if requestCount <= limit {
        return "allowed"
    } else {
        return "limited"
    }
}

The braces are mandatory. Go does not allow you to omit them, even when the branch contains only one statement.

You also do not need parentheses around the condition.

if with an initialization statement

An if statement can include a short initialization statement before its condition. This is useful when a value is only relevant to that decision.

go
func status(requestCount, limit int) string {
    if remaining := limit - requestCount; remaining >= 0 {
        return "allowed"
    }

    return "limited"
}

The variable remaining exists only within the if statement and its associated else branch, if one exists. It cannot be accessed after the if statement.

This keeps temporary variables close to the code that uses them.

for is Go's only loop

Go has no separate while or do while keyword. The for statement covers the common looping patterns.

A traditional loop has an initialization, a condition, and an update:

go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}

The three parts mean:

  1. Initialize i to zero.
  2. Continue while i is less than five.
  3. Increment i after each iteration.

You can also use for with only a condition. This behaves like a while loop in other languages.

go
count := 0

for count < 5 {
    count++
}

A loop without a condition runs indefinitely until it is stopped with break or a return from the surrounding function.

go
for {
    fmt.Println("waiting")
    break
}

range for iterating

The range keyword lets you iterate over values in collections and other supported types. You will use it with slices and maps in the next lesson.

For now, consider a variadic function:

go
func totalRequests(counts ...int) int {
    total := 0

    for _, count := range counts {
        total += count
    }

    return total
}

The range loop produces an index and a value. The blank identifier _ tells Go that you intentionally do not need the index.

You can also use the index:

go
for index, count := range counts {
    fmt.Println(index, count)
}

If you only need the index, you can omit the second variable:

go
for index := range counts {
    fmt.Println(index)
}

Go does not allow you to declare a variable and leave it unused. If you do not need a value, use _ or do not declare it.

switch for multiple choices

A switch is useful when one value can match several alternatives.

go
func responseStatus(code int) string {
    switch code {
    case 200:
        return "success"
    case 429:
        return "rate limited"
    case 500:
        return "server error"
    default:
        return "unknown"
    }
}

Go automatically stops after the matching case. You do not need break at the end of each case.

You can also switch on conditions without providing a value:

go
func classify(requestCount, limit int) string {
    switch {
    case requestCount < 0:
        return "invalid"
    case requestCount <= limit:
        return "allowed"
    default:
        return "limited"
    }
}

This is useful when several related conditions determine a result.

Scope and shadowing

Scope describes where a declared name can be accessed. A variable declared inside a function is generally available from its declaration until the end of its enclosing block.

go
func main() {
    limit := 100

    if limit > 0 {
        message := "limit is configured"
        fmt.Println(message)
    }

    fmt.Println(limit)
}

The variable limit is available throughout main. The variable message exists only inside the if block.

Shadowing happens when a new variable uses the same name as a variable in an outer scope.

go
func main() {
    limit := 100

    if true {
        limit := 50
        fmt.Println(limit)
    }

    fmt.Println(limit)
}

The inner limit is a new variable. It does not update the outer one. The output is:

50
100

This can cause subtle bugs when you accidentally use := instead of =.

go
func main() {
    remaining := 100

    if true {
        remaining := 50
        fmt.Println(remaining)
    }

    fmt.Println(remaining)
}

The second declaration shadows the first. If you intended to update the existing variable, write remaining = 50.

Printing and formatting values

The fmt package provides functions for writing formatted output. You will use it frequently when experimenting with small programs and inspecting values.

fmt.Println prints values separated by spaces and adds a newline.

go
fmt.Println("request count:", 42)

fmt.Printf lets you control how values are formatted using format verbs.

VerbMeaningExample
%vDefault representationfmt.Printf("%v", true)
%dDecimal integerfmt.Printf("%d", 42)
%sStringfmt.Printf("%s", "allowed")
%qQuoted stringfmt.Printf("%q", "allowed")

For example:

go
package main

import "fmt"

func main() {
    count := 42
    status := "allowed"

    fmt.Printf("count=%d status=%s\n", count, status)
    fmt.Printf("status as quoted text: %q\n", status)
}

The %q verb is useful when you want to see the quotation marks around a string. This can help reveal leading or trailing whitespace.

The format verb should match the value you are printing. When experimenting, %v is a useful general-purpose choice.

The comma-ok pattern

Some Go operations return a value and a boolean that tells you whether the operation succeeded. This is commonly called the comma-ok pattern.

You will see it when working with maps, so this is only a preview.

A map lookup can return two values: the value associated with a key and a boolean indicating whether the key exists.

go
value, ok := someMap["user-42"]

If ok is true, the key exists. If it is false, the key is absent. The exact behavior of maps will be covered in the next lesson.

The important idea is that Go often makes success information explicit through multiple return values rather than hiding it.

Defer: cleanup when a function returns

A deferred call is a function call scheduled to run when the surrounding function is about to return. The defer keyword is commonly used for cleanup.

For example, when a function opens a file, it should close that file before returning. You will see the same pattern later with database connections and other resources.

Here is a small example that does not require a file:

go
package main

import "fmt"

func processRequest() {
    fmt.Println("starting request")

    defer fmt.Println("cleanup complete")

    fmt.Println("processing request")
}

func main() {
    processRequest()
}

Output:

starting request
processing request
cleanup complete

The deferred call runs after the ordinary statements in the function have completed.

Deferred calls run last-in, first-out

When a function has multiple deferred calls, they execute in reverse order of declaration. This is called last-in, first-out, or LIFO.

go
package main

import "fmt"

func processRequest() {
    defer fmt.Println("first defer")
    defer fmt.Println("second defer")
    defer fmt.Println("third defer")

    fmt.Println("returning")
}

func main() {
    processRequest()
}

Output:

returning
third defer
second defer
first defer

The last deferred call is executed first.

Show a function declaring three deferred calls in order 1, 2, 3, then returning, with execution shown in reverse order 3, 2, 1 after the return.Show a function declaring three deferred calls in order 1, 2, 3, then returning, with execution shown in reverse order 3, 2, 1 after the return.

This behavior is useful when cleanup operations depend on one another. If a function acquires resources in a particular order, deferring their cleanup often releases them in the reverse order.

Deferred arguments are evaluated immediately

There is an important detail: the arguments to a deferred function call are evaluated when the defer statement executes, not when the function eventually returns.

go
package main

import "fmt"

func main() {
    count := 10

    defer fmt.Println("count:", count)

    count = 20
    fmt.Println("updated count:", count)
}

Output:

updated count: 20
count: 10

The deferred call captured the value 10 when it was declared.

If you need to read a variable when the deferred call runs, use an anonymous function:

go
package main

import "fmt"

func main() {
    count := 10

    defer func() {
        fmt.Println("count:", count)
    }()

    count = 20
}

Output:

count: 20

The anonymous function reads count when it executes, so it sees the updated value.

Defer with early returns

A useful property of defer is that it runs when the function returns, regardless of which return statement is reached.

go
package main

import "fmt"

func processRequest(valid bool) {
    defer fmt.Println("request cleanup")

    if !valid {
        fmt.Println("request rejected")
        return
    }

    fmt.Println("request accepted")
}

func main() {
    processRequest(false)
    processRequest(true)
}

The cleanup message appears after each call, including the call that returns early.

This makes defer particularly useful for cleanup that must happen on every exit path.

Putting the pieces together

The following program combines variables, constants, functions, multiple return values, control flow, and formatting. It models a small rate-limit decision without introducing structs, pointers, slices, maps, methods, or interfaces.

first-program.go
package main

import (
    "fmt"
)

const defaultLimit = 5

func remainingRequests(requestCount, limit int) (int, error) {
    if requestCount < 0 {
        return 0, fmt.Errorf("request count cannot be negative")
    }

    if limit < 0 {
        return 0, fmt.Errorf("limit cannot be negative")
    }

    return limit - requestCount, nil
}

func decide(requestCount, limit int) string {
    if remaining, err := remainingRequests(requestCount, limit); err != nil {
        return "invalid request count"
    } else if remaining == 0 {
        return "limit reached"
    }

    return "request allowed"
}

func main() {
    requestCount := 3
    limit := defaultLimit

    defer fmt.Println("finished checking request")

    result := decide(requestCount, limit)
    fmt.Printf("request count: %d\n", requestCount)
    fmt.Printf("limit: %d\n", limit)
    fmt.Printf("decision: %s\n", result)
}

The program demonstrates several important ideas:

  • defaultLimit is a constant because it does not change.
  • requestCount and limit are variables because their values can change.
  • remainingRequests returns a result and an error.
  • decide uses an if initialization statement to keep temporary values local.
  • main defers a call that runs when the function returns.
  • fmt.Printf prints values using explicit format verbs.

To run it, save the file as first-program.go and execute:

bash
gofmt -w first-program.go
go run first-program.go

gofmt is Go's standard formatter. It applies the formatting rules expected by the Go toolchain. Go code is normally formatted before it is committed, and the formatter removes many style disagreements that would otherwise appear in code reviews.

You can also run the program's package tests with:

bash
go test ./...

At this point, you have enough language knowledge to write a small Go program and understand the basic structure of the code you will build in the next lessons.

Common mistakes to avoid

  • Using := outside a function. Use var or const at package level.
  • Using := when you meant to update an existing variable. Check for shadowing inside nested blocks.
  • Expecting integer division to produce a fractional result. Convert operands to float64 when needed.
  • Forgetting to check an error returned by a function. Check it before using the result.
  • Assuming switch cases fall through automatically. Go stops after a matching case unless you explicitly request fallthrough.
  • Expecting deferred calls to run in declaration order. They execute in LIFO order.
  • Assuming a deferred call reads the latest value of its arguments. Arguments are evaluated when the defer statement executes.
  • Declaring variables that are never used. Go treats unused local variables as compilation errors.

Knowledge assessment

Question 1 of 4

Which statement correctly distinguishes var limit int, limit := 100, and const limit = 100?

Pick an answer, then say how sure you are.

Practical applications

  • Practice exercise 1.8, Write your first Go program: Use variable declarations, constants, functions, return values, control flow, and formatting to write and run a small program.
  • Exercise 1.11: Use functions, errors, conditions, and basic Go syntax when implementing the next rate-limiter component.
  • Exercise 1.14: Use these language fundamentals when working with the rate limiter's types and behavior.
  • Exercise 1.15: Use functions, return values, and control flow to implement and validate additional limiter behavior.
  • Exercise 1.18: Use closures and function values when working with the injected clock.
  • Exercise 1.19: Use error handling, functions, and deferred cleanup in the next backend implementation.
  • Exercise 1.22: Apply the same Go fundamentals when integrating and testing the later components.

These concepts remain useful throughout the rest of the course. Every Go exercise builds on the same basic habits: make values explicit, keep functions focused, check errors, and make cleanup predictable.

References

Everything above is explained on this page; these are where it comes from (Go 1.2x).

Finished Lesson 1.4?