mirror of
https://github.com/golang/go
synced 2024-11-02 11:50:30 +00:00
ccbfbb1c33
Added new test typeparam/factimp.go and changed a bunch of other tests to test exporting more generic functions and types. Change-Id: I573d75431cc92482f8f908695cfbc8e84dbb36d2 Reviewed-on: https://go-review.googlesource.com/c/go/+/321749 Trust: Dan Scales <danscales@google.com> Reviewed-by: Keith Randall <khr@golang.org>
46 lines
941 B
Go
46 lines
941 B
Go
// run -gcflags=-G=3
|
|
|
|
// Copyright 2021 The Go Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
// Index returns the index of x in s, or -1 if not found.
|
|
func Index[T comparable](s []T, x T) int {
|
|
for i, v := range s {
|
|
// v and x are type T, which has the comparable
|
|
// constraint, so we can use == here.
|
|
if v == x {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
type obj struct {
|
|
x int
|
|
}
|
|
|
|
func main() {
|
|
want := 2
|
|
|
|
vec1 := []string{"ab", "cd", "ef"}
|
|
if got := Index(vec1, "ef"); got != want {
|
|
panic(fmt.Sprintf("got %d, want %d", got, want))
|
|
}
|
|
|
|
vec2 := []byte{'c', '6', '@'}
|
|
if got := Index(vec2, '@'); got != want {
|
|
panic(fmt.Sprintf("got %d, want %d", got, want))
|
|
}
|
|
|
|
vec3 := []*obj{&obj{2}, &obj{42}, &obj{1}}
|
|
if got := Index(vec3, vec3[2]); got != want {
|
|
panic(fmt.Sprintf("got %d, want %d", got, want))
|
|
}
|
|
}
|