在Go中返回值而不是指针

In the "net/http" package of Go, there is an interface called ResponseWriter. This interface has a method called Header() Header. Since the Header value that Header() returns is a value and not a pointer, I assumed the function would not be returning the actual Header value that is private to the ResponseWriter but rather a copy.

However, this does not appear to be the case. The docs for ResponseWriter show r.Header().Add("key", "value") to be the proper way to add a header to your http response.

I dug in a little deeper and found the definition for the Header type. It is type Header map[string][]string. I'm a little confused here. Do you not have to return a pointer in this case in order to modify the value that the ResponseWriter has? If so why?

That's because maps and slices are reference types. Take a look this code:

package main

import (
    "fmt"
)

func main() {
    m1 := make(map[string]string)
    var m2 map[string]string
    m1["one"] = "this is from m1"
    m2 = m1
    m2["two"] = "this is from m2"
    fmt.Printf("%#v
", m1)
}

The output is:

map[string]string{"one":"this is from m1", "two":"this is from m2"}

See/edit in the Go Playground.

This has the same result:

package main

import (
    "fmt"
)

type mymap map[string]string

func main() {
    m1 := make(mymap)
    var m2 mymap
    m1["one"] = "this is from m1"
    m2 = m1
    m2["two"] = "this is from m2"
    fmt.Printf("%#v
", m1)
}

Output:

main.mymap{"one":"this is from m1", "two":"this is from m2"}

See/edit in the Go Playground.