Go

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

发布于 2021-02-01 11:17:37

我试图找到如何检查是否设置了结构属性,但找不到任何方法。

我期待这样的事情,但实际上这是行不通的:

type MyStruct struct {
    property    string
}

test := new(MyStruct)
if test.property {
    //do something with this
}
关注者
0
被浏览
86
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    就像dyoo所说的,nil如果您的struct属性是指针,则可以使用。如果您想将它们保留为字符串,可以与进行比较""。这是一个示例:

    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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看