Skip to content

Commit 1506179

Browse files
author
Sean Sorrell
committed
more experimenting with generics
This approach might be workable, but I don't see how just yet
1 parent a7c50d4 commit 1506179

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

types/directives.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
*
3+
* Experimental code with generics
4+
*
5+
**/
6+
package types
7+
8+
import (
9+
"context"
10+
)
11+
12+
// we must express this type as an interface that the Go type checker can assert on
13+
// this duplicates code elsewhere in the `types` package
14+
type InputValue interface {
15+
string | int32
16+
}
17+
18+
type OutputValue interface {
19+
string
20+
}
21+
22+
// generic interface with type parameter
23+
type BeforeVisitor[In InputValue] interface {
24+
Before(context.Context, Directive, In) error
25+
}
26+
27+
type AfterVisitor[Out OutputValue] interface {
28+
After(context.Context, Directive, Out) (Out, error)
29+
}
30+
31+
type DirectiveVisitorI[In InputValue, Out OutputValue] interface {
32+
BeforeVisitor[In]
33+
AfterVisitor[Out]
34+
}
35+
36+
type customDirectiveImpl struct {
37+
}
38+
39+
// OK: compiles
40+
var _ DirectiveVisitorI[string,string] = &customDirectiveImpl{}
41+
42+
// error: "any" does not implement InputValue
43+
var _ DirectiveVisitorI[any,any] = &customDirectiveImpl{}
44+
45+
// error: cannot use type InputValue outside of type constraint, contains type constraints
46+
//
47+
// error: *customDirectiveImpl does not implement DirectiveVisitorI[InputValue, OutputValue] (wrong type for After method)
48+
// have After(ctx context.Context, dir Directive, _ string) (string, error)
49+
// want After(context.Context, Directive, OutputValue) (OutputValue, error) (go-build)
50+
//
51+
var _ DirectiveVisitorI[InputValue, OutputValue] = &customDirectiveImpl{}
52+
53+
func (v *customDirectiveImpl) Before(ctx context.Context, dir Directive, _ string) error {
54+
return nil
55+
}
56+
57+
func (v *customDirectiveImpl) After(ctx context.Context, dir Directive, _ string) (string, error) {
58+
return "", nil
59+
}
60+
61+

0 commit comments

Comments
 (0)