结构体变量如何判断是否为空

liuzhen007
• 阅读 2365

目录

前言

正文

前言

使用任何编程语言都会遇到判空的问题,那么Golang语言是如何对结构体变量判空的呢?说真的,这种方式我还是很意外的。

正文

我们都知道根据语言自身定义的不同,每种语言表示空对象的方式都不同。比如,在JS和Java中是 null,在C和C++中是 NULL。那么在Golang中又是如何表示空对象的呢?

是的,确实和上述语言不一样,Golang表示空对象用 nil。

那么,我们接下来看一下nil的具体定义。

源码:

// nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.

var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
1
2
3

通过上述定义信息,我们可以知道 nil 的适配类型必须是指针、通道、方法、接口、map、切片。别的类型是不能用nil来进行判空的。

那如果我们判断一个结构体类型,特别是一个自定义的结构体对象是否为空时,应该怎么操作呢?

说到Golang对结构体的判空机制,确实刷新了我的认知,多少有些丑 ^_^,特别是对于自定义的结构体类型,并不是简单的与 nil 做比较。

直接上代码:

package main
 
import (
	"fmt"
)

// 自定义一个Person类型的结构体
type Person struct {
	Name string
	Age int
}

func main() {
        // 定义一个Person类型的对象 one,注意定义方式和Java、C++是反着的,类或结构体在后边
	var one Person
	one.Name = "xiaoming"
	one.Age = 12

        // 定义一个Person类型的对象 two
	var two Person
        
        // 今天的重点:如何判空
	if one != (Person{}) {
		fmt.Println(one.Name, "的年龄是", one.Age)
	} else {
		fmt.Println("the person is nil")
	}

        // 今天的重点:如何判空
	if two != (Person{}) {
		fmt.Println(two.Name, "的年龄是", two.Age)
	} else {
		fmt.Println("the person is nil")
	}

	// if two != nil {
	// 	fmt.Println(two.Name, "的年龄是", two.Age)
	// } else {
	// 	fmt.Println("the persion is nil")
	// }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

代码结果:

xiaoming 的年龄是 12
the person is nil

如果放开上面代码的注释,编译器会提示如下错误信息:

command-line-arguments
./nil.go:32:9: invalid operation: two != nil (mismatched types Person and nil)
1
2
点赞
收藏
评论区
推荐文章

暂无数据

liuzhen007
liuzhen007
Lv1
男 · 多媒体研发工程师
敲代码,搞开发。 本人深耕音视频技术,走全栈路线,前后端通吃,兼顾各端与流媒体服务器。 博客主页地址:https://liuzhen.blog.csdn.net 微信公众号:玩转音视频 欢迎沟通学习!
文章
11
粉丝
1
获赞
0