dongxin2734 2014-08-17 12:01
浏览 304
已采纳

验证struct变量是否为空

First of all, look at the following code snippet:

package main

import (
    "fmt"
)

func main() {

    var para1 struct {
        email, addr string
    }

    para1.email = "test@test.com"

    if para1 != nil {
        fmt.Println(para1)
    }

}

When I compile this code, I've got the compiler error:

./struct_func.go:15: cannot convert nil to type struct { email string; addr string }

How can I validate if my struct variable, if nil or not? Or I have to validate of property like

if para1.email != nil {
    fmt.Println(para1)
}
  • 写回答

3条回答 默认 最新

  • dsmgcse8876 2014-08-17 14:15
    关注

    You can compare the struct to its zero value. You can test the string for its zero (empty) value "" or test for string length zero. For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var para1 struct {
            email, addr string
        }
        para1Zero := para1
        para1.email = "test@test.com"
        if para1 != para1Zero {
            fmt.Println(para1)
        }
        if para1.email != "" {
            fmt.Println(para1.email)
        }
        if len(para1.email) != 0 {
            fmt.Println(para1.email)
        }
    }
    

    Output:

    {test@test.com }
    test@test.com
    test@test.com
    

    The Go Programming Language Specification

    The zero value

    When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog