| 1 |
// run |
| 2 |
|
| 3 |
// Copyright 2021 The Go Authors. All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
// Testing various generic uses of indexing, both for reads and writes. |
| 8 |
|
| 9 |
package main |
| 10 |
|
| 11 |
import "fmt" |
| 12 |
|
| 13 |
// Can index an argument (read/write) constrained to be a slice or an array. |
| 14 |
func Index1[T interface{ []int64 | [5]int64 }](x T) int64 { |
| 15 |
x[2] = 5 |
| 16 |
return x[3] |
| 17 |
} |
| 18 |
|
| 19 |
// Can index an argument (read) constrained to be a byte array or a string. |
| 20 |
func Index2[T interface{ []byte | string }](x T) byte { |
| 21 |
return x[3] |
| 22 |
} |
| 23 |
|
| 24 |
// Can index an argument (write) constrained to be a byte array, but not a string. |
| 25 |
func Index2a[T interface{ []byte }](x T) byte { |
| 26 |
x[2] = 'b' |
| 27 |
return x[3] |
| 28 |
} |
| 29 |
|
| 30 |
// Can index an argument (read/write) constrained to be a map. Maps can't |
| 31 |
// be combined with any other type for indexing purposes. |
| 32 |
func Index3[T interface{ map[int]int64 }](x T) int64 { |
| 33 |
x[2] = 43 |
| 34 |
return x[3] |
| 35 |
} |
| 36 |
|
| 37 |
// But the type of the map keys or values can be parameterized. |
| 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 |
} |