Source file test/typeparam/stringer.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  // Test method calls on type parameters
     8  
     9  package main
    10  
    11  import (
    12  	"fmt"
    13  	"reflect"
    14  	"strconv"
    15  )
    16  
    17  // Simple constraint
    18  type Stringer interface {
    19  	String() string
    20  }
    21  
    22  func stringify[T Stringer](s []T) (ret []string) {
    23  	for _, v := range s {
    24  		ret = append(ret, v.String())
    25  	}
    26  	return ret
    27  }
    28  
    29  type myint int
    30  
    31  func (i myint) String() string {
    32  	return strconv.Itoa(int(i))
    33  }
    34  
    35  // Constraint with an embedded interface, but still only requires String()
    36  type Stringer2 interface {
    37  	CanBeStringer2() int
    38  	SubStringer2
    39  }
    40  
    41  type SubStringer2 interface {
    42  	CanBeSubStringer2() int
    43  	String() string
    44  }
    45  
    46  func stringify2[T Stringer2](s []T) (ret []string) {
    47  	for _, v := range s {
    48  		ret = append(ret, v.String())
    49  	}
    50  	return ret
    51  }
    52  
    53  func (myint) CanBeStringer2() int {
    54  	return 0
    55  }
    56  
    57  func (myint) CanBeSubStringer2() int {
    58  	return 0
    59  }
    60  
    61  // Test use of method values that are not called
    62  func stringify3[T Stringer](s []T) (ret []string) {
    63  	for _, v := range s {
    64  		f := v.String
    65  		ret = append(ret, f())
    66  	}
    67  	return ret
    68  }
    69  
    70  func main() {
    71  	x := []myint{myint(1), myint(2), myint(3)}
    72  
    73  	got := stringify(x)
    74  	want := []string{"1", "2", "3"}
    75  	if !reflect.DeepEqual(got, want) {
    76  		panic(fmt.Sprintf("got %s, want %s", got, want))
    77  	}
    78  
    79  	got = stringify2(x)
    80  	if !reflect.DeepEqual(got, want) {
    81  		panic(fmt.Sprintf("got %s, want %s", got, want))
    82  	}
    83  
    84  	got = stringify3(x)
    85  	if !reflect.DeepEqual(got, want) {
    86  		panic(fmt.Sprintf("got %s, want %s", got, want))
    87  	}
    88  }
    89  

View as plain text