drxnfdx798517235 2017-10-28 00:10
浏览 86

如何在Golang中检查指向结构net.IPNet的Pointer的nil值

How can I check the nil value as a result of the assignment of variable b below?

package main

import (
    "fmt"
    "net"
)


type Subnet struct {
    ID                int
    IP                *net.IPNet
}

func main() {
    var s = Subnet{
        ID: 12345,
        IP: &net.IPNet{
            IP:   net.IP{10, 1, 232, 0},
            Mask: net.IPMask{255, 255, 255, 0},
        },
    }
    fmt.Printf("%+v
", s)
    var b = Subnet{
        ID: 12345,
        IP: &net.IPNet{},
    }
    fmt.Printf("%+v
", b)
    if b.IP == nil {
        fmt.Println("hello there")
    }
}

Here is the go playground https://play.golang.org/p/Jk6_3ofyH5

Basically, I expect that "hello there" will be printed out as b.IP is nil, but it did not.

  • 写回答

4条回答 默认 最新

  • doukao5073 2017-10-28 02:38
    关注

    The check should be like, if b.IP != nil { fmt.Println("hello there") } And the output will have hello-world,

    {ID:12345 IP:10.1.232.0/24} {ID:12345 IP:} hello there

    Note:Golang's nil is not same as Cpp's NULL, it is the opposite.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)