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// Test method calls on type parameters8 9package main10 11import (12 "fmt"13 "reflect"14 "strconv"15)16 17// Simple constraint18type Stringer interface {19 String() string20}21 22func stringify[T Stringer](s []T) (ret []string) {23 for _, v := range s {24 ret = append(ret, v.String())25 }26 return ret27}28 29type myint int30 31func (i myint) String() string {32 return strconv.Itoa(int(i))33}34 35// Constraint with an embedded interface, but still only requires String()36type Stringer2 interface {37 CanBeStringer2() int38 SubStringer239}40 41type SubStringer2 interface {42 CanBeSubStringer2() int43 String() string44}45 46func stringify2[T Stringer2](s []T) (ret []string) {47 for _, v := range s {48 ret = append(ret, v.String())49 }50 return ret51}52 53func (myint) CanBeStringer2() int {54 return 055}56 57func (myint) CanBeSubStringer2() int {58 return 059}60 61// Test use of method values that are not called62func stringify3[T Stringer](s []T) (ret []string) {63 for _, v := range s {64 f := v.String65 ret = append(ret, f())66 }67 return ret68}69 70func 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 