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?

图片转代码服务由CSDN问答提供 功能建议

我偶然发现了一个定义自己的请求和响应类型的函数。

  func doSomething(){
 
类型请求结构{
 resourceID字符串
} 
 
类型响应结构{
 resourceContents * Data 
} 
 
 request:= initializeRequest  ()
结果:= dispatchRequest(request)
 
 ... 
} 
   
 
 

我认为这具有记录文档结构的巨大优势 功能主体中的请求和响应权限。 当许多这样的函数在同一个文件中并且它们的请求和响应结构都具有不同的类型时,这样做的便利性尤其明显:在函数外部定义类型意味着我必须用不同的方式命名它们。

尽管如此,我仍然担心这样做的代价: 拥有一个函数调用来声明自己的类型比在包范围内声明该类型是否昂贵得多? \ n

而且,这种方法是惯用的吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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?

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题