diff options
Diffstat (limited to 'test/typeparam/settable.go')
-rw-r--r-- | test/typeparam/settable.go | 27 |
1 files changed, 24 insertions, 3 deletions
diff --git a/test/typeparam/settable.go b/test/typeparam/settable.go index 3bd141f784..7532953a77 100644 --- a/test/typeparam/settable.go +++ b/test/typeparam/settable.go @@ -11,7 +11,24 @@ import ( "strconv" ) -func fromStrings3[T any](s []string, set func(*T, string)) []T { +type Setter[B any] interface { + Set(string) + type *B +} + +func fromStrings1[T any, PT Setter[T]](s []string) []T { + result := make([]T, len(s)) + for i, v := range s { + // The type of &result[i] is *T which is in the type list + // of Setter, so we can convert it to PT. + p := PT(&result[i]) + // PT has a Set method. + p.Set(v) + } + return result +} + +func fromStrings2[T any](s []string, set func(*T, string)) []T { results := make([]T, len(s)) for i, v := range s { set(&results[i], v) @@ -30,8 +47,12 @@ func (p *Settable) Set(s string) { } func main() { - s := fromStrings3([]string{"1"}, - func(p *Settable, s string) { p.Set(s) }) + s := fromStrings1[Settable, *Settable]([]string{"1"}) + if len(s) != 1 || s[0] != 1 { + panic(fmt.Sprintf("got %v, want %v", s, []int{1})) + } + + s = fromStrings2([]string{"1"}, func(p *Settable, s string) { p.Set(s) }) if len(s) != 1 || s[0] != 1 { panic(fmt.Sprintf("got %v, want %v", s, []int{1})) } |