1
2
3
4
5
6
7
8
9 package main
10
11 import "fmt"
12
13
14 func Index1[T interface{ []int64 | [5]int64 }](x T) int64 {
15 x[2] = 5
16 return x[3]
17 }
18
19
20 func Index2[T interface{ []byte | string }](x T) byte {
21 return x[3]
22 }
23
24
25 func Index2a[T interface{ []byte }](x T) byte {
26 x[2] = 'b'
27 return x[3]
28 }
29
30
31
32 func Index3[T interface{ map[int]int64 }](x T) int64 {
33 x[2] = 43
34 return x[3]
35 }
36
37
38 func Index4[T any](x map[int]T) T {
39 var zero T
40 x[2] = zero
41 return x[3]
42 }
43
44 func test[T comparable](got, want T) {
45 if got != want {
46 panic(fmt.Sprintf("got %v, want %v", got, want))
47 }
48 }
49
50 func main() {
51 x := make([]int64, 4)
52 x[3] = 2
53 y := [5]int64{1, 2, 3, 4, 5}
54 z := "abcd"
55 w := make([]byte, 4)
56 w[3] = 5
57 v := make(map[int]int64)
58 v[3] = 18
59
60 test(Index1(x), int64(2))
61 test(Index1(y), int64(4))
62 test(Index2(z), byte(100))
63 test(Index2(w), byte(5))
64 test(Index2a(w), byte(5))
65 test(Index3(v), int64(18))
66 test(Index4(v), int64(18))
67 }
68
View as plain text