ProgramGuru

Function Programs

Start with Function Programs

Learn function programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of function programs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Functions make repeated calculations reusable and testable. They can accept parameters, return multiple values and report errors without relying on globals.

The example implements a safe integer division function that returns both the result and an error.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for example functionsReturn values make a function contract explicit.Call functionStep 1Validate argumentsStep 2Compute or errorStep 3Handle both outputsStep 4Return values make a function contract explicit.
Return values make a function contract explicit.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, fmt.Errorf("division by zero")
	}
	return a / b, nil
}
func main() {
	for _, pair := range [][2]int{{20, 4}, {20, 0}} {
		result, err := divide(pair[0], pair[1])
		fmt.Println("Result:", result, "Error:", err)
	}
}

Output

Result: 5 Error: <nil>
Result: 0 Error: division by zero

Trace what the program does

The first call yields 5 with no error. The second call detects a zero divisor and returns an error rather than panicking.

Avoid common mistakes

  • Integer division truncates toward zero; it does not compute a fractional float result.
  • Do not ignore an error return from a function just because an example happens to succeed.

Try it yourself

Change divide to return a float64 result while still reporting a zero-divisor error.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Why return an error as a second value?
Choose one answer. You can try again.

Answer and explanation

To let callers distinguish valid results from failure

Correct. The first call yields 5 with no error.

What you should remember

You have practiced Function Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Recursion Programs →