1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package tinferenceB
6
7 import "strconv"
8
9 type any interface{}
10
11 // TODO(rFindley) the below partially applied function types should probably
12 // not be permitted (spec question).
13
14 func f0[A any, B interface{type C}, C interface{type D}, D interface{type A}](A, B, C, D)
15 func _() {
16 f := f0[string]
17 f("a", "b", "c", "d")
18 f0("a", "b", "c", "d")
19 }
20
21 func f1[A any, B interface{type A}](A, B)
22 func _() {
23 f := f1[int]
24 f(int(0), int(0))
25 f1(int(0), int(0))
26 }
27
28 func f2[A any, B interface{type []A}](A, B)
29 func _() {
30 f := f2[byte]
31 f(byte(0), []byte{})
32 f2(byte(0), []byte{})
33 }
34
35 func f3[A any, B interface{type C}, C interface{type *A}](A, B, C)
36 func _() {
37 f := f3[int]
38 var x int
39 f(x, &x, &x)
40 f3(x, &x, &x)
41 }
42
43 func f4[A any, B interface{type []C}, C interface{type *A}](A, B, C)
44 func _() {
45 f := f4[int]
46 var x int
47 f(x, []*int{}, &x)
48 f4(x, []*int{}, &x)
49 }
50
51 func f5[A interface{type struct{b B; c C}}, B any, C interface{type *B}](x B) A
52 func _() {
53 x := f5(1.2)
54 var _ float64 = x.b
55 var _ float64 = *x.c
56 }
57
58 func f6[A any, B interface{type struct{f []A}}](B) A
59 func _() {
60 x := f6(struct{f []string}{})
61 var _ string = x
62 }
63
64 // TODO(gri) Need to flag invalid recursive constraints. At the
65 // moment these cause infinite recursions and stack overflow.
66 // func f7[A interface{type B}, B interface{type A}]()
67
68 // More realistic examples
69
70 func Double[S interface{ type []E }, E interface{ type int, int8, int16, int32, int64 }](s S) S {
71 r := make(S, len(s))
72 for i, v := range s {
73 r[i] = v + v
74 }
75 return r
76 }
77
78 type MySlice []int
79
80 var _ = Double(MySlice{1})
81
82 // From the draft design.
83
84 type Setter[B any] interface {
85 Set(string)
86 type *B
87 }
88
89 func FromStrings[T interface{}, PT Setter[T]](s []string) []T {
90 result := make([]T, len(s))
91 for i, v := range s {
92 // The type of &result[i] is *T which is in the type list
93 // of Setter2, so we can convert it to PT.
94 p := PT(&result[i])
95 // PT has a Set method.
96 p.Set(v)
97 }
98 return result
99 }
100
101 type Settable int
102
103 func (p *Settable) Set(s string) {
104 i, _ := strconv.Atoi(s) // real code should not ignore the error
105 *p = Settable(i)
106 }
107
108 var _ = FromStrings[Settable]([]string{"1", "2"})
109
View as plain text