0

I have a function that returns an anonymous struct. This function is generated and so I cannot change the code or create a type for the return value.

func foo() struct {
    Prop int
} {
    result := new(struct {
        Prop int
    })
    result.Prop = 1
    return *result
}

In other places in the codebase, I want to define a function, bar() that accepts as an argument the return type of foo()

func bar(arg ReturnTypeOfFoo) {
    // ...
}

Can I do this without manually defining the ReturnTypeOfFoo type? Is there some kind of reflection I can do on foo()?

2 Answers 2

2

You may use the same anonymous struct as the parameter type for bar():

func bar(arg struct {
    Prop int
}) {
    fmt.Printf("Received: %+v\n", arg)
}

Then the following is valid code:

res := foo()
bar(res)

And outputs (try it on the Go Playground):

Received: {Prop:1}

This is possible because the call bar(res) is valid if all arguments are assignable to the parameter types of bar(), and the anonymous struct return type of foo() is assignable to the anonymous struct parameter of bar().

If you need this to be dynamic (e.g. the result type of foo() may change when re-generated), you may use the go/parser package to parse the generated source, and generate bar() with identical parameter type, idiomatically executed when go generate is run. You should make this part of the generation process that generates / changes foo, so foo and bar will be in sync.

1
  • Adding a 2nd generation step is a great recommendation. Thank you!
    – ryanrhall
    Jan 7, 2021 at 21:10
1

Can I do this without manually defining the ReturnTypeOfFoo type?

No, because ...

Is there some kind of reflection I can do on foo()?

No. You cannot use reflection at compile time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.