Prevent duplicate initialisation #1196
-
I would like to fulfil an interface while also providing the struct that fulfils that interface. Using package main
import "go.uber.org/fx"
type Thing1 struct{}
type Thing2 interface{}
func NewThing() *Thing1 {
println("Hello World!")
return &Thing1{}
}
func main() {
// Prints "Hello World!" twice
fx.New(
fx.Provide(
NewThing,
fx.Annotate(NewThing, fx.As(new(Thing2))),
),
fx.Invoke(func(*Thing1, Thing2) {
}),
)
} Is there a shorthand in Fx to ask for |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hey @tumelowill - there currently isn't a satisfying way (that I'm aware of) to provide a type as both itself and as an interface in one line. However, you can avoid duplicate initialization by adding a "constructor" that converts the struct to an interface (see here as well). // Prints "Hello World!" once
fx.New(
fx.Provide(
NewThing,
func(t *Thing1) Thing2 { return t },
),
fx.Invoke(func(*Thing1, Thing2) {
}),
) |
Beta Was this translation helpful? Give feedback.
Hey @tumelowill - there currently isn't a satisfying way (that I'm aware of) to provide a type as both itself and as an interface in one line. However, you can avoid duplicate initialization by adding a "constructor" that converts the struct to an interface (see here as well).