Golang--Go判断结构体类型是否为空(nil)

Golang--Go判断结构体类型是否为空(nil),第1张

自定义的结构体类型,并不是简单的与 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")
	}
}

代码结果:

xiaoming 的年龄是 12
the person is nil

运行结果截图:

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

运行结果截图:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994725.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存