Skip to content

Commit 08eb5da

Browse files
Add a generic BindFor that can usually replace BindTo
When this infers the type of interfaces at compile-time it’s usually more ergonomic.
1 parent 258b13a commit 08eb5da

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

options.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,13 @@ func BindTo(impl, iface any) Option {
248248
})
249249
}
250250

251+
// BindFor allows binding of implementations to the compile-time type. It
252+
// is equivalent to BindTo(v, (*T)(nil)), but can usually infer the
253+
// correct type T.
254+
func BindFor[T any](v T) Option {
255+
return BindTo(v, (*T)(nil))
256+
}
257+
251258
// BindToProvider binds an injected value to a provider function.
252259
//
253260
// The provider function must have one of the following signatures:

options_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package kong
22

33
import (
4+
"context"
45
"reflect"
56
"strings"
67
"testing"
@@ -43,6 +44,23 @@ func TestBindTo(t *testing.T) {
4344
assert.Equal(t, "foo", saw)
4445
}
4546

47+
func TestBindFor(t *testing.T) {
48+
type key struct{}
49+
var saw any
50+
method := func(ctx context.Context) error {
51+
saw = ctx.Value(key{})
52+
return nil
53+
}
54+
55+
var cli struct{}
56+
57+
p, err := New(&cli, BindFor(context.WithValue(context.Background(), key{}, "foo")))
58+
assert.NoError(t, err)
59+
err = callFunction(reflect.ValueOf(method), p.bindings)
60+
assert.NoError(t, err)
61+
assert.Equal(t, "foo", saw)
62+
}
63+
4664
func TestInvalidCallback(t *testing.T) {
4765
type iface interface {
4866
Method()

0 commit comments

Comments
 (0)