我试图找到如何设置结构属性,但我找不到任何方法.
我希望像这样的东西但是这样的麻烦不起作用:
type MyStruct struct {
property string
}
test := new(MyStruct)
if test.property {
//do something with this
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*ews 12
就像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")
}
}
Run Code Online (Sandbox Code Playgroud)
http://play.golang.org/p/YStKFuekeZ
您可以使用指针及其nil
值来确定是否已设置某些内容。例如,如果您将结构更改为
type MyStruct struct {
property *string
}
Run Code Online (Sandbox Code Playgroud)
然后property
可以指向一个字符串值(在这种情况下已设置),也可以指向nil
,在这种情况下尚未设置。这是protobuf库用来确定是否设置字段的一种方法,如您在https://code.google.com/p/goprotobuf/source/browse/README#83中所见
除了 Charlie 的回答和(某种程度上)回答 asafel 的问题之外,如果属性的类型不是字符串,您可以检查 Go 分配给该特定类型的默认值,如下所示:
type MyStruct struct {
Str string
Bool bool
Int int
Uint uint
}
func main() {
s := MyStruct{}
fmt.Println(s.Str)
fmt.Println(s.Bool)
fmt.Println(s.Int)
fmt.Println(s.Uint)
}
Run Code Online (Sandbox Code Playgroud)
输出:
""
false
0
0
Run Code Online (Sandbox Code Playgroud)
并且您可以检查结构中是否设置了值“
""
false
0
0
Run Code Online (Sandbox Code Playgroud)
正如您可能已经注意到的,从技术上讲,您无法真正检查该属性是否已设置,但我认为这是对查理答案的一个值得补充
归档时间: |
|
查看次数: |
21917 次 |
最近记录: |