douying2243 2018-05-25 06:17
浏览 538
已采纳

为什么建议使用ctx作为第一个参数?

I'm new to golang. As the documentation said

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx

but I found, in the typical http request handle function, a http.Request object has .Context() method can retrieve the context which http request assoicate with.

So why recommand use context as first parameter in theses function. Is that reasonable in this situation?


I know that is not a restrict rule. But I wan't to know why the HandlerFunc is func(ResponseWriter, *Request) instead of func(context.Context, ResponseWriter, *Request)

Apparently, HandlerFunc break the recommandation.

  • 写回答

1条回答 默认 最新

  • douyue2313 2018-05-25 07:10
    关注

    As described in the documentation you quoted above, ctx should be a (very) common argument for many functions. This is similar to the way many functions return an error. The best place for a common argument/return value is either as the first, or last in a list. (Arguably, Go could have chosen to make error always be the first return value--I won't discuss that here).

    Since variadic variables may only be the last in the list of function arguments, this leaves the only option for a common argument to be the first one.

    I expect this is why ctx is always first.

    This pattern is often seen with other variables in Go (and other languages) as well. Any time a common variable is used by a set of related functions, that common variable often comes first in the argument list (or possibly second, after ctx).


    Contrary to the advice you quoted, there are libraries that store ctx in a struct, rather than passing it around as the first argument. These are usually (always?) libraries which had to be retro-fitted to use ctx, long after the library contract was set in stone (by the Go 1.x compatibility guarantee).

    Generally, you should follow the advice to pass ctx as the first argument, for any new work.

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

报告相同问题?

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?