diff --git a/options.go b/options.go index 5792c12..ba7d747 100644 --- a/options.go +++ b/options.go @@ -248,6 +248,13 @@ func BindTo(impl, iface any) Option { }) } +// BindFor allows binding of implementations to the compile-time type. It +// is equivalent to BindTo(v, (*T)(nil)), but can usually infer the +// correct type T. +func BindFor[T any](v T) Option { + return BindTo(v, (*T)(nil)) +} + // BindToProvider binds an injected value to a provider function. // // The provider function must have one of the following signatures: diff --git a/options_test.go b/options_test.go index 791cb64..db2a3c7 100644 --- a/options_test.go +++ b/options_test.go @@ -1,6 +1,7 @@ package kong import ( + "context" "reflect" "strings" "testing" @@ -43,6 +44,23 @@ func TestBindTo(t *testing.T) { assert.Equal(t, "foo", saw) } +func TestBindFor(t *testing.T) { + type key struct{} + var saw any + method := func(ctx context.Context) error { + saw = ctx.Value(key{}) + return nil + } + + var cli struct{} + + p, err := New(&cli, BindFor(context.WithValue(context.Background(), key{}, "foo"))) + assert.NoError(t, err) + err = callFunction(reflect.ValueOf(method), p.bindings) + assert.NoError(t, err) + assert.Equal(t, "foo", saw) +} + func TestInvalidCallback(t *testing.T) { type iface interface { Method()