Golang中如何校验struct是否为空?

作者: aries 分类: Go 发布时间: 2020-05-21 20:15 ė 1139次浏览 6 0评论

在Golang中,空结构的大小为0。这里,空结构的意思是,结构中没有字段。

比如有这样一个结构体:

Type structure_name struct {
}

检查结构体是否为空的方法应该有很多

方法1:

package main

import (
"fmt"
)

type Person struct {

}

func main() {
var st Person
if (Person{} == st) {
fmt.Println("It is an empty structure")
} else {
fmt.Println("It is not an empty structure")
}
}

方法2:

package main

import (
"fmt"
)

type Person struct {
age int
}

func main() {
var st Person
if (Person{20} == st) {
fmt.Println("It is an empty structure")
} else {
fmt.Println("It is not an empty structure")
}
}

如果一个结构有字段,那么如何检查结构是否被初始化?

package main

import (
"fmt"
"reflect"
)

type Person struct {
age int
}

func (x Person) IsStructureEmpty() bool {
return reflect.DeepEqual(x, Person{})
}

func main() {
x := Person{}

if x.IsStructureEmpty() {
fmt.Println("Structure is empty")
} else {
fmt.Println("Structure is not empty")
}
}

换一个
暂无评论
Ɣ回顶部