doujiang1993 2018-08-27 08:09
浏览 526
已采纳

struct映射的默认值是什么

What is the default value of struct in a map? How to check the map value is initialized?

type someStruct struct { 
    field1 int
    field2 string
}
var mapping map[int]someStruct

func main() {
    mapping := make(map[int]someStruct)
}

func check(key int) {
    if mapping[key] == ? {}
}

Should I check against nil or someStruct{}?

  • 写回答

1条回答 默认 最新

  • dt2002 2018-08-27 08:14
    关注

    Default value of a struct is zero value for each field which is different on basis of its type.

    When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" 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.

    type T struct { i int; f float64; next *T }
    t := new(T)
    

    the following holds:

    t.i == 0
    t.f == 0.0
    t.next == nil
    

    But for checking the value of a map based on the key if it exists you can use it as:

    i, ok := m["route"]
    

    In this statement, the first value (i) is assigned the value stored under the key "route". If that key doesn't exist, i is the value type's zero value (0). The second value (ok) is a bool that is true if the key exists in the map, and false if not.

    For your question

    Should I check against nil or someStruct{} ?

    To check for initialized empty struct you can check for someStruct{} as:

    package main
    
    import (
        "fmt"
    )
    
    type someStruct struct { 
        field1 int
        field2 string
    }
    var mapping map[int]someStruct
    
    func main() {
        var some someStruct
        fmt.Println(some == (someStruct{}))
        //mapping := make(map[int]someStruct)
    }
    

    Go playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料