Source file test/typeparam/index.go

     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  package main
     8  
     9  import (
    10  	"fmt"
    11  )
    12  
    13  // Index returns the index of x in s, or -1 if not found.
    14  func Index[T comparable](s []T, x T) int {
    15  	for i, v := range s {
    16  		// v and x are type T, which has the comparable
    17  		// constraint, so we can use == here.
    18  		if v == x {
    19  			return i
    20  		}
    21  	}
    22  	return -1
    23  }
    24  
    25  type obj struct {
    26  	x int
    27  }
    28  
    29  type obj2 struct {
    30  	x int8
    31  	y float64
    32  }
    33  
    34  type obj3 struct {
    35  	x int64
    36  	y int8
    37  }
    38  
    39  type inner struct {
    40  	y int64
    41  	z int32
    42  }
    43  
    44  type obj4 struct {
    45  	x int32
    46  	s inner
    47  }
    48  
    49  func main() {
    50  	want := 2
    51  
    52  	vec1 := []string{"ab", "cd", "ef"}
    53  	if got := Index(vec1, "ef"); got != want {
    54  		panic(fmt.Sprintf("got %d, want %d", got, want))
    55  	}
    56  
    57  	vec2 := []byte{'c', '6', '@'}
    58  	if got := Index(vec2, '@'); got != want {
    59  		panic(fmt.Sprintf("got %d, want %d", got, want))
    60  	}
    61  
    62  	vec3 := []*obj{&obj{2}, &obj{42}, &obj{1}}
    63  	if got := Index(vec3, vec3[2]); got != want {
    64  		panic(fmt.Sprintf("got %d, want %d", got, want))
    65  	}
    66  
    67  	vec4 := []obj2{obj2{2, 3.0}, obj2{3, 4.0}, obj2{4, 5.0}}
    68  	if got := Index(vec4, vec4[2]); got != want {
    69  		panic(fmt.Sprintf("got %d, want %d", got, want))
    70  	}
    71  
    72  	vec5 := []obj3{obj3{2, 3}, obj3{3, 4}, obj3{4, 5}}
    73  	if got := Index(vec5, vec5[2]); got != want {
    74  		panic(fmt.Sprintf("got %d, want %d", got, want))
    75  	}
    76  
    77  	vec6 := []obj4{obj4{2, inner{3, 4}}, obj4{3, inner{4, 5}}, obj4{4, inner{5, 6}}}
    78  	if got := Index(vec6, vec6[2]); got != want {
    79  		panic(fmt.Sprintf("got %d, want %d", got, want))
    80  	}
    81  }
    82  

View as plain text