Result Objects¶
A result object is an object with the sole purpose of carrying results for a specific function or method.
As with parameter objects, the object is defined exclusively for a single function, and not shared with other functions.
In Fx, result objects contain exported fields exclusively,
and are always tagged with fx.Out
.
Related
- Parameter objects are the parameter analog of result objects.
Using result objects¶
To use result objects in Fx, take the following steps:
-
Define a new struct type named after your constructor with a
Result
suffix. If the constructor is namedNewClient
, name the structClientResult
. If the constructor is namedNew
, name the structResult
. This naming isn't strictly necessary, but it's a good convention to follow.type ClientResult struct { }
-
Embed
fx.Out
into this struct.type ClientResult struct { fx.Out
-
Use this new type as the return value of your constructor by value.
func NewClient() (ClientResult, error) {
-
Add values produced by your constructor as exported fields on this struct.
type ClientResult struct { fx.Out Client *Client }
-
Set these fields and return an instance of this struct from your constructor.
func NewClient() (ClientResult, error) { client := &Client{ // ... } return ClientResult{Client: client}, nil }
Once you have a result object on a function, you can use it to access other advanced features of Fx:
Adding new results¶
You can add new values to an existing result object in a completely backwards compatible manner.
-
Take an existing result object.
type Result struct { fx.Out Client *Client } func New() (Result, error) { client := &Client{ // ... } return Result{ Client: client, }, nil
-
Add a new field to it for your new result.
type Result struct { fx.Out Client *Client Inspector *Inspector }
-
In your constructor, set this field.
return Result{ Client: client, Inspector: &Inspector{ // ... }, }, nil