説明なし

constraint_inference3.go 1007B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. type Settable int
  7. func (p *Settable) Set(s string) {
  8. i, _ := strconv.Atoi(s) // real code should not ignore the error
  9. *p = Settable(i)
  10. }
  11. // SETTER2 OMIT
  12. type Setter2[B any] interface {
  13. Set(string)
  14. *B // non-interface type constraint element
  15. }
  16. func FromStrings2[T any, PT Setter2[T]](s []string) []T {
  17. result := make([]T, len(s))
  18. for i, v := range s {
  19. // The type of &result[i] is *T which is in the type set
  20. // of Setter2, so we can convert it to PT.
  21. p := PT(&result[i])
  22. p.Set(v) // PT has a Set method.
  23. }
  24. return result
  25. }
  26. // SETTER2 OMIT
  27. func main(){
  28. // FromStrings2 takes two type parameters.
  29. // The second parameter must be a pointer to the first.
  30. // Settable is as above.
  31. // SETTER2 CALL OMIT
  32. nums := FromStrings2[Settable, *Settable]([]string{"1", "2"})
  33. // Now nums is []Settable{1, 2}.
  34. fmt.Println(nums)
  35. // SETTER2 CALL OMIT
  36. /**
  37. // SETTER3 CALL OMIT
  38. nums := FromStrings2[Settable]([]string{"1", "2"})
  39. // SETTER3 CALL OMIT
  40. */
  41. }