广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Go语言中nil判断引起的问题详析
  • 248
分享到

Go语言中nil判断引起的问题详析

2024-04-02 19:04:59 248人浏览 八月长安
摘要

前言 代码封装是百干不厌的事,但有时候封装会导致一些问题。本文记录了个人在封装 Http 请求时遇到的一个和 nil 判断有关的问题。 nil 是什么 在 Go 语言中,布尔类型的

前言

代码封装是百干不厌的事,但有时候封装会导致一些问题。本文记录了个人在封装 Http 请求时遇到的一个和 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判断引起问题的文章就介绍到这了,更多相关Go nil判断问题内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

您可能感兴趣的文档:

--结束END--

本文标题: Go语言中nil判断引起的问题详析

本文链接: https://www.lsjlt.com/news/128359.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作