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!