| // run |
| |
| // Copyright 2020 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 ( |
| "log" |
| "strconv" |
| ) |
| |
| type Setter[B any] interface { |
| Set(string) |
| type *B |
| } |
| |
| func FromStrings[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 |
| } |
| |
| type Settable int |
| |
| func (p *Settable) Set(s string) { |
| i, err := strconv.Atoi(s) |
| if err != nil { |
| log.Fatal(err) |
| } |
| *p = Settable(i) |
| } |
| |
| func main() { |
| s := FromStrings[Settable, *Settable]([]string{"1"}) |
| if len(s) != 1 || s[0] != 1 { |
| log.Fatalf("got %v, want %v", s, []int{1}) |
| } |
| } |