A question about usages of Go example functions in the testing package

Viewed 48

In package main:

package main

func main(){}

In package main_test, I create an example function named ExampleClient(). And it is actually the example code in package go-redis's README.md file.

package main_test

import (
    ...

    "github.com/go-redis/redis/v9"
)

var ctx = context.Background()

// The example function in the document of package go-redis.
func ExampleClient() {
    ...
    // Output: key value
    // key2 does not exist
}

Above code does not have any warnings. But I didn't create a func named Client() in the main package. Why doesn't Go tool hint: "ExampleXxx refers to unknown identifier: Xxx" towards example function using go-redis package, like ExampleClient(), ExampleConn(), etc? Where does the go tool find the Client() func? In "github.com/go-redis/redis/v9"?

This is another example function in the another package for comparison.

package another

func main(){}

In package another_test, no import of package "github.com/go-redis/redis/v9".

package another_test

func ExampleClient() {
    // Do nothing.
    ...
}

With above code, go tool hints: ExampleClient refers to unknown identifier: Client, because I didn't create a func named Client() in main package neither. This behavior meets my expectations.

Why are the above two behaviors inconsistent? Are there any rules about the usages of Go example functions I missed?

0 Answers
Related