Go判断结构体类型是否为空(nil)
发布日期:2021-06-30 21:12:50 浏览次数:2 分类:技术文章

本文共 832 字,大约阅读时间需要 2 分钟。

目录

 


前言

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

正文

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

直接上代码:

package main import (	"fmt")type Person struct {	Name string	Age int}func main() {	var one Person	one.Name = "xiaoming"	one.Age = 12	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) 

运行结果截图:

转载地址:https://liuzhen.blog.csdn.net/article/details/112667774 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:记录第一次参加CSDN博客之星评选(2020)
下一篇:Electron理论知识 16 - Electron 11.0 高亮发布

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月16日 21时56分57秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章