codekingpro/portable-devtools
114k
1// run2 3// Copyright 2021 The Go Authors. All rights reserved.4// Use of this source code is governed by a BSD-style5// license that can be found in the LICENSE file.6 7// Testing various generic uses of indexing, both for reads and writes.8 9package main10 11import "fmt"12 13// Can index an argument (read/write) constrained to be a slice or an array.14func Index1[T interface{ []int64 | [5]int64 }](x T) int64 {15 x[2] = 516 return x[3]17}18 19// Can index an argument (read) constrained to be a byte array or a string.20func 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.25func 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't31// be combined with any other type for indexing purposes.32func Index3[T interface{ map[int]int64 }](x T) int64 {33 x[2] = 4334 return x[3]35}36 37// But the type of the map keys or values can be parameterized.38func Index4[T any](x map[int]T) T {39 var zero T40 x[2] = zero41 return x[3]42}43 44func test[T comparable](got, want T) {45 if got != want {46 panic(fmt.Sprintf("got %v, want %v", got, want))47 }48}49 50func main() {51 x := make([]int64, 4)52 x[3] = 253 y := [5]int64{1, 2, 3, 4, 5}54 z := "abcd"55 w := make([]byte, 4)56 w[3] = 557 v := make(map[int]int64)58 v[3] = 1859 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 