我正在研究http 的源代碼Golang,我發(fā)現(xiàn)了這個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)}函數(shù)Get傳遞nil給函數(shù)NewRequest,函數(shù)NewRequest將 this 傳遞nil給函數(shù)NewRequestWithContext,那么函數(shù) NewRequestWithContext用來nil調(diào)用nil.(io.ReadCloser),為什么不引起panic呢?
2 回答

素胚勾勒不出你
TA貢獻1827條經(jīng)驗 獲得超9個贊
該聲明
rc, ok := body.(io.ReadCloser)
測試是否body
為 ReadCloser
. 如果不是,rc
則將設(shè)置為nil
,并將ok
設(shè)置為false
。
如果代碼是:
rc:=body.(io.ReadCloser)
然后用一個零的身體,它會驚慌失措。
- 2 回答
- 0 關(guān)注
- 96 瀏覽
添加回答
舉報
0/150
提交
取消