dongqun1656 2013-12-12 21:02
浏览 21
已采纳

如何检查是否在结构中设置了属性

I am trying to find how check if a structure property was set, but i cannot find any way.

I expect something like this but of corse this not works:

type MyStruct struct {
    property    string
}

test := new(MyStruct)
if test.property {
    //do something with this
}
  • 写回答

3条回答 默认 最新

  • dsyak22488 2013-12-12 21:58
    关注

    Like dyoo said, you can use nil if your struct properties are pointers. If you want to keep them as strings you can compare with "". Here is a sample:

    package main
    
    import "fmt"
    
    type MyStruct struct {
        Property string
    }
    
    func main() {
        s1 := MyStruct{
            Property: "hey",
        }
    
        s2 := MyStruct{}
    
        if s1.Property != "" {
            fmt.Println("s1.Property has been set")
        }
    
        if s2.Property == "" {
            fmt.Println("s2.Property has not been set")
        }
    }
    

    http://play.golang.org/p/YStKFuekeZ

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大