golang判断结构体为空
The size of an empty structure is zero in Golang. Here, empty structure means, there is no field in the structure.
在Golang中, 空结构的大小为零。 在此, 空结构表示该结构中没有字段。
Eg:
例如:
Type structure_name struct {
}
There are many ways to check if structure is empty. Examples are given below.
有很多方法可以检查结构是否为空 。 示例如下。
Example 1:
范例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")
}
}
It is an empty structure
Example 2:
范例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")
}
}
It is not an empty structure
If a structure has fields, then how to check whether structure has been initialised or not?
如果结构具有字段,那么如何检查结构是否已初始化?
Please follow given below examples...
请遵循以下示例...
Syntax:
句法:
Type structure_name struct {
variable_name type
}
Example 1:
范例1:
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")
}
}
Output
输出量
Structure is empty
Example 2:
范例2:
package main
import (
"fmt"
"reflect"
)
type Person struct {
age int
}
func (x Person) IsStructureEmpty() bool {
return reflect.DeepEqual(x, Person{})
}
func main() {
x := Person{}
x.age = 20
if x.IsStructureEmpty() {
fmt.Println("Structure is empty")
} else {
fmt.Println("Structure is not empty")
}
}
Output
输出量
Structure is not empty
Using switch statement
使用switch语句
Example 1:
范例1:
package main
import (
"fmt"
)
type Person struct {
}
func main() {
x := Person{}
switch {
case x == Person{}:
fmt.Println("Structure is empty")
default:
fmt.Println("Structure is not empty")
}
}
Output
输出量
Structure is empty
Example 2:
范例2:
package main
import (
"fmt"
)
type Person struct {
age int
}
func main() {
x := Person{}
switch {
case x == Person{1}:
fmt.Println("Structure is empty")
default:
fmt.Println("Structure is not empty")
}
}
Output
输出量
Structure is not empty
翻译自: https://www.includehelp.com/golang/how-to-check-if-structure-is-empty.aspx
golang判断结构体为空