【golang基础】判定字符串为空、判断结构体是否已经初始化、两个结构体是否相等

本文介绍了在Golang中如何判定字符串是否为空、判断结构体是否已初始化以及如何使用`reflect.DeepEqual`比较两个数据结构是否相等。内容包括对空结构的理解和结构体值的检查方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串是否为空

    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值