You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have had much grief figuring out my problem and I realized that fx.Populate() wants a provided constructor returning a struct, not a pointer. Why is that? Consider this example
In this case, what is printed is:
{name2}
{name2}
If we of course, reverse this, having NewState2() return a pointer and instead NewState1() return the struct, we'll end up with
{name1}
{name1}
Why is that? fx.Populate()'s documentation is not clear on this.
fx.Populate's documentation states "All targets must be pointers to the values that must be populated". So this means that if you pass fx.Populate a value of type *State, it will populate that value with a State. The example you linked is passing the same type to fx.Populate twice, of which there is only a single value in the container: that returned by NewState2, so both pointers you pass in will be populated with the same value.
NewState1 returns a different type: *State. If you want to retrieve that, you'd need to pass a double-pointer to fx.Populate, a var of type **State:
var (
state1 *State
state2 State
)
app := fx.New(
fx.Populate(&state1), // gets set to "name1"
fx.Populate(&state2), // gets set to "name2"
// ...
)
If you'd rather both NewState1 and NewState2 return just a State (no pointer), I'd suggest you look into Annotations, specifically fx.ParamTags and fx.ResultTags, which allow multiple values of the same type to exist in the container. fx.Populate is compatible with annotations as well (see example in fx.Populate documentation).
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have had much grief figuring out my problem and I realized that
fx.Populate()
wants a provided constructor returning a struct, not a pointer. Why is that? Consider this exampleIn this case, what is printed is:
If we of course, reverse this, having
NewState2()
return a pointer and insteadNewState1()
return the struct, we'll end up withWhy is that?
fx.Populate()
's documentation is not clear on this.Beta Was this translation helpful? Give feedback.
All reactions