Are maps passed by value or by reference in Go?

前端 未结 3 1804
北恋
北恋 2021-01-30 05:10

Are maps passed by value or reference in Go ?

It is always possible to define a function as following, but is this an overkill ?

func foo(dat *map[string         


        
3条回答
  •  孤独总比滥情好
    2021-01-30 05:30

    No. Maps are reference by default.

        package main
    
        import "fmt"
    
        func mapToAnotherFunction(m map[string]int) {
            m["hello"] = 3
            m["world"] = 4
            m["new_word"] = 5
        }
    
        // func mapToAnotherFunctionAsRef(m *map[string]int) {
        // m["hello"] = 30
        // m["world"] = 40
        // m["2ndFunction"] = 5
        // }
    
        func main() {
            m := make(map[string]int)
            m["hello"] = 1
            m["world"] = 2
    
            // Initial State
            for key, val := range m {
                fmt.Println(key, "=>", val)
            }
    
            fmt.Println("-----------------------")
    
            mapToAnotherFunction(m)
            // After Passing to the function as a pointer
            for key, val := range m {
                fmt.Println(key, "=>", val)
            }
    
            // Try Un Commenting This Line
            fmt.Println("-----------------------")
    
            // mapToAnotherFunctionAsRef(&m)
            // // After Passing to the function as a pointer
            // for key, val := range m {
            //  fmt.Println(key, "=>", val)
            // }
    
            // Outputs
            // hello => 1
            // world => 2
            // -----------------------
            // hello => 3
            // world => 4
            // new_word => 5
            // -----------------------
    
        }
    

    From Golang Blog-

    Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function:

    // Ex of make function
    m = make(map[string]int)
    

    Code Snippet Link Play with it.

提交回复
热议问题