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

huangapple go评论75阅读模式
英文:

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)
    ...
}

但是这个bodynil,它是通过以下方式传递的:

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)
}

函数Getnil传递给函数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将被设置为nilok将被设置为false

如果代码是这样的:

rc := body.(io.ReadCloser)

那么当bodynil时,它将引发恐慌。

英文:

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.

huangapple
  • 本文由 发表于 2022年1月14日 08:49:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/70704858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定