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 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: