google / wire

Compile-time Dependency Injection for Go
Apache License 2.0
13.07k stars 622 forks source link

wire.NewSet support generics #381

Open OldSmokeGun opened 1 year ago

OldSmokeGun commented 1 year ago

Describe the bug

Wire doesn't support generics when I pass a generic function in wire.NewSet

To Reproduce

Pass generic function in wire.NewSet, like this:

wire.NewSet(
    db.New[config.DBConfigDefault, config.DBInstanceDefault],
    ent.New,
    redis.New,
    discovery.New,
    casbin.New,
    grpc.New,
    uid.New,
)

or

var ProviderSet = wire.NewSet(
    GetApp,
    GetHTTP,
    GetGRPC,
    GetDB[DBKeyDefault, DBConfigDefault],
    GetRedis,
    GetTrace,
    GetDiscovery,
    GetServices,
    GetJWT,
    GetCasbin,
)

Then, wire reports an error like this:

$ wire
wire: /example/internal/config/config.go:16:2: unknown pattern
wire: /example/internal/app/app.go:27:3: unknown pattern
wire: /example/internal/config/config.go:16:2: unknown pattern
wire: /example/internal/app/app.go:27:3: unknown pattern
wire: /example/internal/app/app.go:27:3: unknown pattern
wire: /example/internal/command: generate failed
wire: at least one generate failure

Expected behavior

can generate code correctly

Version

github.com/google/wire v0.5.1-0.20220620021424-0675cdc9191c

Additional context

Here is my code:

func GetDB[K DBKeyGetter, V DBConfigGroup]() (V, error) {
    c, err := getEntry(config.DB)
    if err != nil {
        return V{}, err
    }
    var k K
    return V(c[k.GetName()]), nil
}
func New[C config.DBConfigGroup, D config.DBInstanceGroup](conf C, logger *slog.Logger) (db D, cleanup func(), err error) {
        // code
}
Hamper commented 7 months ago

You can use workaround like this

wire.NewSet(
    newDb,
    ent.New,
    redis.New,
    discovery.New,
    casbin.New,
    grpc.New,
    uid.New,
)

func newDb(conf config.DBConfigDefault, logger *slog.Logger) (db config.DBInstanceDefault, cleanup func(), err error) {
    return db.New[config.DBConfigDefault, config.DBInstanceDefault]
}