首先,请看下面的代码片段:
package main
import (
"fmt"
)
func main() {
var para1 struct {
email, addr string
}
para1.email = "[email protected]"
if para1 != nil {
fmt.Println(para1)
}
}
编译此代码时,出现编译器错误:
./struct_func.go:15: cannot convert nil to type struct { email string; addr string }
如何验证我的结构变量是否为nil?或者我必须验证诸如
if para1.email != nil {
fmt.Println(para1)
}
最佳答案
您可以将struct
与其零值进行比较。您可以测试string
的零(空)值""
或测试string
的长度零。例如,
package main
import (
"fmt"
)
func main() {
var para1 struct {
email, addr string
}
para1Zero := para1
para1.email = "[email protected]"
if para1 != para1Zero {
fmt.Println(para1)
}
if para1.email != "" {
fmt.Println(para1.email)
}
if len(para1.email) != 0 {
fmt.Println(para1.email)
}
}
输出:
{[email protected] }
[email protected]
[email protected]
关于go - 验证struct变量是否为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25349004/