dongzhang2150 2019-01-17 13:48
浏览 117
已采纳

在函数调用中定义golang结构的成本

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?

  • 写回答

1条回答 默认 最新

  • dongshao5573 2019-01-17 14:21
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现