Examples are both documentation and tests. They're useful for demonstrating usage, providing executable documentation, and ensuring examples stay up to date.
Basic example
package main
import "fmt"
func ExampleAdd() {
result := Add(2, 3)
fmt.Println(result)
// Output: 5
}
Examples must be in *_test.go files, start with Example, and include an // Output: comment. The testing framework verifies that the output matches the comment.
Example with output
func ExampleGreet() {
fmt.Println(Greet("Alice"))
// Output: Hello, Alice!
}