Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default value of a map of 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{}?

like image 786
tbraden Avatar asked Aug 27 '18 08:08

tbraden


1 Answers

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

like image 130
Himanshu Avatar answered Nov 10 '22 23:11

Himanshu