...
1
2
3
4
5 package test
6
7 import (
8 "fmt"
9 "sort"
10 "testing"
11 )
12
13
14 func genericSorted[T sort.Interface](data T) bool {
15 n := data.Len()
16 for i := n - 1; i > 0; i-- {
17 if data.Less(i, i-1) {
18 return false
19 }
20 }
21 return true
22 }
23 func TestGenericSorted(t *testing.T) {
24 var data = sort.IntSlice{-10, -5, 0, 1, 2, 3, 5, 7, 11, 100, 100, 100, 1000, 10000}
25 f := func() {
26 genericSorted(data)
27 }
28 if n := testing.AllocsPerRun(10, f); n > 0 {
29 t.Errorf("got %f allocs, want 0", n)
30 }
31 }
32
33
34
35 type fooer interface {
36 foo()
37 }
38 type P struct {
39 p *int
40 q int
41 }
42
43 var esc []*int
44
45 func (p P) foo() {
46 esc = append(esc, p.p)
47 }
48 func f[T fooer](t T) {
49 t.foo()
50 }
51 func TestGenericEscape(t *testing.T) {
52 for i := 0; i < 4; i++ {
53 var x int = 77 + i
54 var p P = P{p: &x}
55 f(p)
56 }
57 for i, p := range esc {
58 if got, want := *p, 77+i; got != want {
59 panic(fmt.Sprintf("entry %d: got %d, want %d", i, got, want))
60 }
61 }
62 }
63
View as plain text