溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Go語言中nil判斷出問題如何解決

發(fā)布時間:2022-04-15 14:03:16 來源:億速云 閱讀:328 作者:iii 欄目:編程語言

這篇文章主要介紹“Go語言中nil判斷出問題如何解決”,在日常操作中,相信很多人在Go語言中nil判斷出問題如何解決問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Go語言中nil判斷出問題如何解決”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

nil 是什么

在 Go 語言中,布爾類型的零值(初始值)為 false,數(shù)值類型的零值為 0,字符串類型的零值為空字符串"",而指針、切片、映射、通道、函數(shù)和接口的零值則是 nil。

nil 內(nèi)置的一個變量,用來代表空值,且只有指針、channel、方法、接口、map 和切片可以被賦值為 nil。

有過其他編程語言開發(fā)經(jīng)驗的開發(fā)者也許會把 nil 看作其他語言中的 null(NULL),其實這并不是完全正確的,因為Go語言中的 nil 和其他語言中的 null 有很多不同點。

buildin/buildin.go:

// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type

// Type is here for the purposes of documentation only. It is a stand-in
// for any Go type, but represents the same type for any given function
// invocation.
type Type int

問題代碼

下面的代碼是我對 http.Post 方法的封裝

func (r *Request) Post(endpoint string, params *url.Values, body io.Reader, headers map[string]string, cookies map[string]string) (resp *http.Response, err error) {
    url := fmt.Sprintf("%s%s", r.BaseURL, endpoint)
    var req *http.Request
    req, err = http.NewRequest(http.MethodPost, url, body)
    if err != nil {
        return
    }
    r.setRequest(req, params, headers, cookies)
    resp, err = r.Client.Do(req)
    return
}

然后像下面這樣使用的時候:

var body *bytes.Reader
body = nil

resp, err = req.Post(endpoint, nil, body, nil, nil)

這時會出現(xiàn)空指針的錯誤,最終經(jīng)過漫長的排查發(fā)現(xiàn)是在 http.NewRequest 里出現(xiàn)的空指針錯誤:

錯誤分析

指針和接口的底層實現(xiàn)有兩部分:data 和 type。當指針和接口被顯式地賦值為 nil 時,data 和 type 同時為 nil,但是將一個 type 不為 nil 但 data 為 nil 的值賦值給指針或接口時,再與 nil 作比較的結(jié)果則是 false。

修改代碼

使用 reflect.ValueOf(body).IsNil() 判斷 body 是否為空:

func (r *Request) Post(endpoint string, params *url.Values, body io.Reader, headers map[string]string, cookies map[string]string) (resp *http.Response, err error) {
    url := fmt.Sprintf("%s%s", r.BaseURL, endpoint)
    var req *http.Request
    if reflect.ValueOf(body).IsNil() {
        req, err = http.NewRequest(http.MethodPost, url, nil)
    } else {
        req, err = http.NewRequest(http.MethodPost, url, body)
    }
    if err != nil {
        return
    }
    r.setRequest(req, params, headers, cookies)
    resp, err = r.Client.Do(req)
    return
}

到此,關(guān)于“Go語言中nil判斷出問題如何解決”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI