Home  >  Article  >  Backend Development  >  How to check null pointer in golang

How to check null pointer in golang

(*-*)浩
(*-*)浩Original
2019-12-31 14:35:327780browse

How to check null pointer in golang

When assigning a null pointer object to an interface                                                                               (recommended learning: go)

   var pi *int = nil
    var i interface{}
    i = pi
    fmt.Println(i == nil) // 结果为 false

This is not the case It is difficult to understand, because i = pi, instead of assigning nil to i, i points to the object pi.

Determine whether the pointer in the interface is null

So, the question now is, how to determine whether the pointer in the interface is null?

When you know the type, you can naturally use type assertion and then judge it to be empty. For example, ai, ok := i.(*int), and then judge ai == nil.

I don’t know what type of pointer it is, so I have to use reflection vi := reflect.ValueOf(i), and then use vi.IsNil() to judge. But if i is not a pointer, an exception will occur when calling IsNil. You may need to write a function like this to detect null

func IsNil(i interface{}) bool {
    defer func() {
        recover()
    }()
    vi := reflect.ValueOf(i)
    return vi.IsNil()}

But it is really not good-looking to impose a defer recover like this, so I use type judgment. It became like this

func IsNil(i interface{}) bool {
    vi := reflect.ValueOf(i)
    if vi.Kind() == reflect.Ptr {
        return vi.IsNil()
    }
    return false
}

The above is the detailed content of How to check null pointer in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn