Search code examples
gostructtype-declaration

Cost of defining golang structs on function call


I've stumbled upon a function that defines its own request and response types.

func doSomething() {

    type request struct {
        resourceID string
    }

    type response struct {
        resourceContents *Data
    }

    request := initializeRequest()
    result := dispatchRequest(request)

    ...
}

I think this has the great advantage of documenting the structure of the request and response right in the body of the function. The convenience of this is particularly evident when many such functions are in the same file and they all have a different type for their request and response structs: defining the types outside of the function means that I have to name them differently.

I'm concerned about the cost of this, though: Is it much more expensive to have a function call declare its own type vs declaring that type in the package scope?

Also, is this approach idiomatic?


Solution

  • Types are a compile-time concept and their scope won't (generally) affect runtime speed, since the code the compiler generates in these cases is oblivious to the original type (read up more on Type erasure and reification), with reflection being the outlier, but you have no reflection here.


    That said, I find this code a bit suspicious:

    request := initializeRequest()
    

    Where is initializeRequest defined? It has to be aware of the request type, so I assume it's internal to the function as well? Otherwise the code wouldn't compile. These considerations limit the utility of function-local structs in many cases, but if you do have everything local, I think it's a good practice to hide the types as much as possible.

    In larger scale programs, the issue of testing will also come into play. How do you test types and functions working on them if they are hidden in scope?