Go: example with struct as activity return type

The Go SDK documentation on Activities contains this sentence:

The result value can be either a basic type or a struct with the only requirement being that it is serializable.

Would it be possible to add a code sample to temporal-go-examples showing how to use a struct as the argument type to an activity and a return type from an activity?

Should one use the struct by value or by reference (pointer)? I might be talking rubbish here as I don’t have a lot of Go experience, which makes it all the more important to add such a code example.

1 Like

We don’t have a simple example to demonstrate structure as an argument or result of an activity. But Particle Swarm Optimization sample does use structures this way.

The function signature of the activity has the Particle struct type as the return type rather than a pointer to the struct:

This means I can’t write return nil, err in case there is an intermediate error to return. Can I also have it typed with a (*Particle, error)?

I changed the activity code to the following and it worked:

    err := workflow.ExecuteActivity(ctx, InitParticleActivityName, &swarm).Get(ctx, &particle)

func InitParticleActivity(ctx context.Context, swarm *Swarm) (*Particle, error) {
	logger := activity.GetLogger(ctx)
	logger.Info("initParticleActivity started.")

	particle := NewParticle(swarm, rng)
	particle.UpdateFitness(swarm)

	return particle, nil
}
1 Like

Re-asking part of the original question. Sorry if it has somehow been answered already.

This means I can’t write return nil, err in case there is an intermediate error to return

Your example above shows returning a pointer to a struct from an activity. But, in the workflow, how do I get nil or the struct ?

For example, the following code doesn’t work in the workflow.

var particle *Particle
err := workflow.ExecuteActivity(ctx, InitParticleActivityName, &swarm).Get(ctx, particle)
if particle == nil {
  // do something
} else {
  // do something else
}

The following works, but I can’t check whether the return value was nil.

var particle Particle
err := workflow.ExecuteActivity(ctx, InitParticleActivityName, &swarm).Get(ctx, &particle)

For anything you want to decode into a value, you can pass a pointer for it to see if it was nil. So if you return *Particle from the activity, you can pass a **Particle into the Get call. Try changing .Get(ctx, particle) to .Get(ctx, &particle) in your first set of code there.

1 Like

Hi @Chad_Retz, that works. Thank you so much.