Home  >  Article  >  Backend Development  >  How to determine whether a pointer is null in golang

How to determine whether a pointer is null in golang

尚
Original
2020-01-13 10:51:596913browse

How to determine whether a pointer is null in golang

Golang’s method of determining whether a pointer is empty:

1. When you know the type, you can naturally use type assertions and then determine whether it is empty. For example, ai, ok := i.(*int), and then judge ai == nil.

2. If I don’t know what type of pointer it is, 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 becomes like this

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

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of How to determine whether a pointer is null 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