结构映射的默认值是什么
What is the default value of a map of struct
映射中struct的默认值是多少?如何查看map值是否初始化?
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] == ? {}
}
我应该检查 nil
还是 someStruct{}
?
结构的默认值是每个字段的零值,根据其类型不同。
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)
以下成立:
t.i == 0
t.f == 0.0
t.next == nil
但是如果要根据键检查映射的值(如果存在),您可以将其用作:
i, ok := m["route"]
在这个语句中,第一个值 (i) 被赋予存储在键 "route" 下的值。如果该键不存在,则 i 是值类型的零值 (0)。第二个值 (ok) 是一个布尔值,如果键存在于映射中则为真,否则为假。
针对您的问题
Should I check against nil or someStruct{} ?
要检查初始化的空结构,您可以检查 someStruct{}
为:
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)
}
映射中struct的默认值是多少?如何查看map值是否初始化?
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] == ? {}
}
我应该检查 nil
还是 someStruct{}
?
结构的默认值是每个字段的零值,根据其类型不同。
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)
以下成立:
t.i == 0
t.f == 0.0
t.next == nil
但是如果要根据键检查映射的值(如果存在),您可以将其用作:
i, ok := m["route"]
在这个语句中,第一个值 (i) 被赋予存储在键 "route" 下的值。如果该键不存在,则 i 是值类型的零值 (0)。第二个值 (ok) 是一个布尔值,如果键存在于映射中则为真,否则为假。
针对您的问题
Should I check against nil or someStruct{} ?
要检查初始化的空结构,您可以检查 someStruct{}
为:
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)
}