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 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题