CodeBlanks Logo Icon CodeBlanks

Example tests

Learn Example functions and output verification.

Example tests

Functions starting with Example are both documentation and tests. The trailing // Output: comment states the expected output; go test compares it, and go doc and pkg.go.dev show the example.

func ExampleTopla() {
    fmt.Println(Topla(2, 3))
    // Output: 5
}

Without an Output line the example is compiled but not run.

Naming rules

An example's name says what it documents: Example() documents the package, ExampleTopla() a function, and ExampleSepet_Ekle() the Ekle method of type Sepet. For several examples of the same item add a lower-case suffix: ExampleTopla_negatif().

Practice Example body

Write the Selam(ad string) string function and an ExampleSelam() function documenting it (with the // Output: Merhaba Ada comment). Call ExampleSelam() in main.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func Selam(ad string) string { return "Merhaba " + ad }

func ExampleSelam() {
    fmt.Println(Selam("Ada"))
    // Output: Merhaba Ada
}

func main() {
    ExampleSelam()
}

Expected output

Merhaba Ada

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is used in an example whose output order is nondeterministic (e.g. iterating a map)?

  • No example can be written
  • // Unordered output: Correct answer
  • // Output:
  • // Random:

Explanation: Unordered output compares the lines while ignoring their order.

2 Expected output

Question
func ExampleSelam() {
    fmt.Println(Selam("Ada"))
    // ____: Merhaba Ada
}
Answer
func ExampleSelam() {
    fmt.Println(Selam("Ada"))
    // Output: Merhaba Ada
}

Explanation: The // Output: comment states the output go test will compare.

3 Example name

Term Meaning
Example() The package
ExampleTopla() The Topla function
ExampleSepet_Ekle() The Sepet.Ekle method
ExampleTopla_negatif() A second example

All lessons in Intermediate