温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Go语言中nil判断出问题如何解决

发布时间:2022-04-15 14:03:16 来源:亿速云 阅读:315 作者:iii 栏目:编程语言

这篇文章主要介绍“Go语言中nil判断出问题如何解决”,在日常操作中,相信很多人在Go语言中nil判断出问题如何解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Go语言中nil判断出问题如何解决”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

nil 是什么

在 Go 语言中,布尔类型的零值(初始值)为 false,数值类型的零值为 0,字符串类型的零值为空字符串"",而指针、切片、映射、通道、函数和接口的零值则是 nil。

nil 内置的一个变量,用来代表空值,且只有指针、channel、方法、接口、map 和切片可以被赋值为 nil。

有过其他编程语言开发经验的开发者也许会把 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)

这时会出现空指针的错误,最终经过漫长的排查发现是在 http.NewRequest 里出现的空指针错误:

错误分析

指针和接口的底层实现有两部分:data 和 type。当指针和接口被显式地赋值为 nil 时,data 和 type 同时为 nil,但是将一个 type 不为 nil 但 data 为 nil 的值赋值给指针或接口时,再与 nil 作比较的结果则是 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
}

到此,关于“Go语言中nil判断出问题如何解决”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI