dtwxt88240 2016-12-23 12:04
浏览 1882

Golang http包:Request.WithContext方法src代码说明

Following is an excerpt from source code of http/request.go line 290:

// WithContext returns a shallow copy of r with its context changed
// to ctx. The provided ctx must be non-nil.
func (r *Request) WithContext(ctx context.Context) *Request {
    if ctx == nil {
        panic("nil context")
    }
    r2 := new(Request)      //
    *r2 = *r                // strange gymnastics
    r2.ctx = ctx            //
    return r2
}

I looked at it for an hour trying to understand last 4 lines. Why is that gymnastics for? Doesn't it means just the following:

r.ctx = ctx
return r

Or do I miss something?

  • 写回答

1条回答 默认 最新

  • donk68254 2016-12-23 13:43
    关注

    Let's examine the lines in question:

    r2 := new(Request)
    

    This is a short variable declaration, creates the r2 variable, and initializes it with the value of the right-hand side expression, which is a call to the builtin new() function, which allocates memory for the given type, and returns a pointer to it (being the zero value of the type).

    *r2 = *r
    

    This line assigns the value pointed by r to the value pointed by r2. Note that this does not assign the pointer value, but the pointed value. Since the pointed value is of type Request which is a struct, the assignment copies the values of the fields.

    r2.ctx = ctx
    

    Since r2 is a pointer to a struct, this is a shorthand for (*r2).ctx = ctx, which assigns the given context value to the ctx field of the value (of type Context) pointed by r2.

    return r2
    

    This r2 pointer is then returned. Note that r2 is a pointer different from r, and the pointed value is a different and independent request from that pointed by r.


    If you would do

    r.ctx = ctx
    return r
    

    It would assign the context to the ctx field pointed by r, and this same r pointer would be returned. The returned value would be identical to the value of r, so both r and the returned value would point to the same Request value, and both would have the new Context value. The original code does not modify the ctx of the original request (the one whose WithContext() method is called).

    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错