为什么我们可以使用`nil`来获取成员

我正在研究http 的源代码Golang,我发现了这个


func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error) {

    ...

    rc, ok := body.(io.ReadCloser)

    ...

}

但这body是nil,它是通过以下方式传递的


func NewRequest(method, url string, body io.Reader) (*Request, error) {

    return NewRequestWithContext(context.Background(), method, url, body)

}

func (c *Client) Get(url string) (resp *Response, err error) {

    req, err := NewRequest("GET", url, nil)

    if err != nil {

        return nil, err

    }

    return c.Do(req)

}

函数Get传递nil给函数NewRequest,


函数NewRequest将 this 传递nil给函数NewRequestWithContext,


那么函数 NewRequestWithContext用来nil调用nil.(io.ReadCloser),为什么不引起panic呢?


红糖糍粑
浏览 70回答 2
2回答

素胚勾勒不出你

该声明    rc, ok := body.(io.ReadCloser)测试是否body为 ReadCloser. 如果不是,rc则将设置为nil,并将ok设置为false。如果代码是:rc:=body.(io.ReadCloser)然后用一个零的身体,它会惊慌失措。

FFIVE

该语句rc, ok := body.(io.ReadCloser)是在赋值特殊形式中使用的类型断言。当body为 nil 时,rc设置为 nil 并ok设置为 false。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go