Açıklama Yok

constraint_inference.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. // DOUBLE DEFINATION OMIT
  3. // Double returns a new slice that contains all the elements of s, doubled.
  4. func Double[E constraints.Integer](s []E) []E {
  5. r := make([]E, len(s))
  6. for i, v := range s {
  7. r[i] = v + v
  8. }
  9. return r
  10. }
  11. var s1 = Double[int]([]int{1,2,3}) // s1 is an int slice with value {2,4,6}
  12. // DOUBLE DEFINATION OMIT
  13. // CALL DOUBLE ERROR OMIT
  14. // MySlice is a slice of ints.
  15. type MySlice []int
  16. // The type of V1 will be []int, not MySlice.
  17. // Here we are using function argument type inference,
  18. // but not constraint type inference.
  19. var V1 = Double(MySlice{1})
  20. // CALL DOUBLE ERROR OMIT
  21. // DOUBLE DEFINED OMIT
  22. // DoubleDefined returns a new slice that contains the elements of s,
  23. // doubled, and also has the same type as s.
  24. func DoubleDefined[S ~[]E, E constraints.Integer](s S) S {
  25. // Note that here we pass S to make, where above we passed []E.
  26. r := make(S, len(s))
  27. for i, v := range s {
  28. r[i] = v + v
  29. }
  30. return r
  31. }
  32. // DOUBLE DEFINED OMIT
  33. // CALL DOUBLE OMIT
  34. // The type of V2 will be MySlice.
  35. var V2 = DoubleDefined[MySlice, int](MySlice{1})
  36. // CALL DOUBLE OMIT
  37. // CALL DOUBLE INFERENCE OMIT
  38. var V3 = DoubleDefined(MySlice{1})
  39. // CALL DOUBLE INFERENCE OMIT
  40. // CALL DOUBLE INFERENCE WHOLE OMIT
  41. var V3 = DoubleDefined[MySlice,int](MySlice{1})
  42. // CALL DOUBLE INFERENCE WHOLE OMIT
  43. // POINTER METHOD OMIT
  44. // Setter is a type constraint that requires that the type
  45. // implement a Set method that sets the value from a string.
  46. type Setter interface {
  47. Set(string)
  48. }
  49. // FromStrings takes a slice of strings and returns a slice of T,
  50. // calling the Set method to set each returned value.
  51. //
  52. // Note that because T is only used for a result parameter,
  53. // function argument type inference does not work when calling
  54. // this function.
  55. func FromStrings[T Setter](s []string) []T {
  56. result := make([]T, len(s))
  57. for i, v := range s {
  58. result[i].Set(v)
  59. }
  60. return result
  61. }
  62. // POINTER METHOD OMIT