Golang如何对结构体变量判空|Go主题月

2,493 阅读2分钟

目录

前言

正文

前言

使用任何编程语言都会遇到判空的问题,那么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 typ

通过上述定义信息,我们可以知道 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")
	// }

}

代码结果:

xiaoming 的年龄是 12
the person is nil

运行结果截图:

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

localhost:test lz$ go run nil.go
# command-line-arguments
./nil.go:32:9: invalid operation: two != nil (mismatched types Person and nil)

运行结果截图: