str := ""
//方式一
if len(str) == 0{
fmt.Println("len(str):string is null")
}
//方式二
if str == "" {
fmt.Println("==:string is null")
}
//运行结果:
//len(str):string is null
//==:string is null
判断结构体是否已经初始化
概念区分:
空结构表示该结构中没有字段。
例如:
type NumStruct struct {
}
以下代码主要也是判断结构体中是否有值,是否已经初始化。
package main
import (
"fmt"
"reflect"
)
type FiveTuple_Input struct {
Protocol string
Saddr string
Sport string
Daddr string
Dport string
}
func (t FiveTuple_Input) IsEmpty() bool {
return reflect.DeepEqual(t, FiveTuple_Input{})
}
func main() {
var testStruct1 FiveTuple_Input
var testStruct2 = FiveTuple_Input{"TCP", "1.1.1.1", "123", "2.2.2.2", "456"}
//方式一
if testStruct1 == (FiveTuple_Input{}) {
fmt.Println("testStruct1 is empty")
} else {
fmt.Println("testStruct1 is not empty")
}
if testStruct2 != (FiveTuple_Input{}) {
fmt.Println("testStruct2 ", testStruct2 ," is not empty")
} else {
fmt.Println("testStruct2 ", testStruct2 ," is empty")
}
//运行结果:
//testStruct1 is empty
//testStruct2 {TCP 1.1.1.1 123 2.2.2.2 456} is not empty
//方式二
if testStruct1.IsEmpty() {
fmt.Println("reflect deep:testStruct1 is empty")
} else {
fmt.Println("reflect deep:testStruct1 is not empty")
}
if !testStruct2.IsEmpty() {
fmt.Println("reflect deep:testStruct2 ", testStruct2 ," is not empty")
} else {
fmt.Println("reflect deep:testStruct2 ", testStruct2 ," is empty")
}
//运行结果:
//reflect deep:testStruct1 is empty
//reflect deep:testStruct2 {TCP 1.1.1.1 123 2.2.2.2 456} is not empty
}
判断数据结构是否相等
reflect.DeepEqual(a, b)
reflect.DeepEqual的使用,可参考:
https://studygolang.com/articles/2194