|
| 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