Go Variables, Functions, and Error Handling
Introduction
Go keeps its core features small. This tutorial covers declaring variables and constants, writing functions, and Go's distinctive approach to errors: functions return an error value instead of throwing exceptions.
Prerequisites
- Go installed
- A module you can run with go run .
Step-by-Step Guide
Step 1: Declare variables and constants
Use var with an explicit type, or the short := form inside functions to declare and infer the type at once. Constants never change.
var name string = "Ava"
age := 30 // short declaration (inside functions only)
const pi = 3.14159
fmt.Println(name, age, pi)Step 2: Write a function
Parameter types come after the names, and the return type comes after the parameter list.
func add(a int, b int) int {
return a + b
}
fmt.Println(add(2, 3)) // 5Step 3: Return multiple values, including an error
By convention, a function that can fail returns its result plus an error as the last value. A nil error means success.
import "errors"
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}Step 4: Check the error
Handle the error immediately after the call, before using the result.
result, err := divide(10, 2)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(result) // 5FAQs
- Why does Go return errors instead of throwing exceptions?
- It makes failure paths explicit in the code. Callers see every place an error can occur and decide how to handle it, rather than relying on exceptions that jump across function boundaries.
- What is the blank identifier _ used for?
- It discards a value you don't need, for example result, _ := divide(1, 2). Go refuses to compile unused variables, so _ is how you intentionally ignore one.
Summary
Use := for quick local variables, return an error as the last value from functions that can fail, and always check it right away. This explicit style is a defining feature of Go code.
Comments
Log in or create a free account to join the discussion.