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) {
("It is an empty structure")
} else {
("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) {
("It is an empty structure")
} else {
("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 (x, Person{})
}
func main() {
x := Person{}
if () {
("Structure is empty")
} else {
("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 (x, Person{})
}
func main() {
x := Person{}
= 20
if () {
("Structure is empty")
} else {
("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{}:
("Structure is empty")
default:
("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}:
("Structure is empty")
default:
("Structure is not empty")
}
}
Output
输出量
Structure is not empty
翻译自: /golang/
golang判断结构体为空