How to determine whether a pointer is null in golang

Release: 2020-01-13 10:51:59
Original
6814 people have browsed it

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() }
Copy after login

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 }
Copy after login

For more golang knowledge, please pay attention to thegolang tutorialcolumn 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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!