英文:
Why can we use `nil` to get members
问题
我正在学习Golang的http源代码,我找到了这个。
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将这个nil传递给函数NewRequestWithContext,
然后函数NewRequestWithContext使用nil调用nil.(io.ReadCloser),为什么不会引发panic?
英文:
I am studying http source codes of Golang, I found this
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error) {
...
rc, ok := body.(io.ReadCloser)
...
}
but this body is nil, it is passed in the following way
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)
}
Function Get passes nil to function NewRequest,
function NewRequest passes this nil to function NewRequestWithContext,
then function NewRequestWithContext use nil to call nil.(io.ReadCloser), why does not it cause panic?
答案1
得分: 5
该语句
rc, ok := body.(io.ReadCloser)
测试body是否为ReadCloser类型。如果不是,则rc将被设置为nil,ok将被设置为false。
如果代码是这样的:
rc := body.(io.ReadCloser)
那么当body为nil时,它将引发恐慌。
英文:
The statement
rc, ok := body.(io.ReadCloser)
tests if body is a ReadCloser. If not, then rc will be set to nil, and ok will be set to false.
If the code was:
rc:=body.(io.ReadCloser)
then with a nil body, it would panic.
答案2
得分: 2
语句rc, ok := body.(io.ReadCloser)是一种在赋值特殊形式中使用的类型断言。当body为nil时,rc被设置为nil,ok被设置为false。
英文:
The statement rc, ok := body.(io.ReadCloser) is a type assertion used in the assignment special form. When body is nil, rc is set to nil and ok is set to false.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论