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

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大