func BenchmarkFunction(b *testing.B) { for i := 0; i < b.N; i++ { // Code to be benchmarked } b.ReportAllocs() }
func TestFunction(t *testing.T) { var tests = []struct { input string expected string }{ {"hello", "llo"}, {"world", "ld"}, } for _, test := range tests { result := substring(test.input) if result != test.expected { t.Errorf("Substring of %s should be %s, got %s instead.", test.input, test.expected, result) } if testing.AllocsPerRun(100, func() { substring(test.input) }) > 0 { t.Errorf("Substring of %s is allocating memory.", test.input) } } }In this example, a test function is defined that tests a `substring` function. The `testing.AllocsPerRun` function is used to check if the `substring` function is allocating memory. If it is, the test fails with an error message. It is worth noting that the `ReportAllocs` method and the `testing.AllocsPerRun` function are part of the testing package of Go. Therefore, their package library is `testing`.