golang判断结构体为空_如何在Golang中检查结构是否为空?
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 mainimport ("fmt" )type Person struct {}func main() {var st Personif (Person{} == st) {fmt.Println("It is an empty structure")} else {fmt.Println("It is not an empty structure")} } It is an empty structureExample 2:
范例2:
package mainimport ("fmt" )type Person struct {age int }func main() {var st Personif (Person{20} == st) {fmt.Println("It is an empty structure")} else {fmt.Println("It is not an empty structure")} } It is not an empty structureIf 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 mainimport ("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 emptyExample 2:
范例2:
package mainimport ("fmt""reflect" )type Person struct {age int }func (x Person) IsStructureEmpty() bool {return reflect.DeepEqual(x, Person{}) }func main() {x := Person{}x.age = 20if x.IsStructureEmpty() {fmt.Println("Structure is empty")} else {fmt.Println("Structure is not empty")} }Output
輸出量
Structure is not emptyUsing switch statement
使用switch語句
Example 1:
范例1:
package mainimport ("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 emptyExample 2:
范例2:
package mainimport ("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判斷結構體為空
總結
以上是生活随笔為你收集整理的golang判断结构体为空_如何在Golang中检查结构是否为空?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java Calendar hashCo
- 下一篇: obj[]与obj._Ruby中带有示例