Нет описания

constraint_inference2.go 1.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package main
  2. import (
  3. "strconv"
  4. )
  5. // Setter is a type constraint that requires that the type
  6. // implement a Set method that sets the value from a string.
  7. type Setter interface {
  8. Set(string)
  9. }
  10. // FromStrings takes a slice of strings and returns a slice of T,
  11. // calling the Set method to set each returned value.
  12. //
  13. // Note that because T is only used for a result parameter,
  14. // function argument type inference does not work when calling
  15. // this function.
  16. func FromStrings[T Setter](s []string) []T {
  17. result := make([]T, len(s))
  18. for i, v := range s {
  19. result[i].Set(v)
  20. }
  21. return result
  22. }
  23. // POINTER METHOD CALL OMIT
  24. // Settable is an integer type that can be set from a string.
  25. type Settable int
  26. // Set sets the value of *p from a string.
  27. func (p *Settable) Set(s string) {
  28. i, _ := strconv.Atoi(s) // real code should not ignore the error
  29. *p = Settable(i)
  30. }
  31. func main() {
  32. // INVALID
  33. nums := FromStrings[Settable]([]string{"1", "2"})
  34. _ = nums
  35. // Here we want nums to be []Settable{1, 2}.
  36. // ...
  37. }
  38. // POINTER METHOD CALL OMIT