简体   繁体   中英

Why functions in Golang are pointers

In the GoLang we can divide all data types into two groups.

Int, Float, Array, Strucs - value types Slice, Map, Func, Interface - pointer types.

I understand why Slice and Map are pointers. For example you can add more values into the map in the different function:

func main() {
    m := make(map[string]string)
    updateMap(m)
    fmt.Println(m)
}

func updateMap(m map[string]string) {
    m["1"] = "1"
    m["2"] = "2"
    m["3"] = "3"
    m["4"] = "4"
}

Slice you can simply update:

func main() {
   s := make([]int, 2)
   s[0] = 0
   s[1] = 0

   updateSlice(s)
   fmt.Println(s)
}

func updateSlice(s []int) {
   s[0] = 1
   s[1] = 1
}

**But what is the reason for func to be a pointer? **

I can't overwrite it:


func main() {
 f := func() {
  fmt.Println("Hello, 世界")
 }

 update(f)
 f()

}

func update(f func()) {
 f = func() {
  fmt.Println(2)
 }
}


So, i really confused why it should be a pointer, why it can't be just an value?

I have an assumption, that this is related to memory managment of the functions. IMHO, if funcs wount be a pinters, we could not do like this:

func main() {
   s := 2
   x := func() {
      s = 3
   }
   updateFunc(x)
   fmt.Println(s)
}

func updateFunc(f func()) {
   f()
}

Functions are not pointers and neither are slices, maps, nor interfaces. Pointers can be dereferenced, but none of the other types can be. Slices and maps are data structures that contain pointers, that's all.

Your updateMap and updateSlice functions are invalid analogies to update(f func()) because they don't assign to the argument. Try for instance:

func updateSlice(s []int) {
   s = []int{}
}

In Go, all arguments are passed by value:

After [the function value and arguments] are evaluated, the parameters of the call are passed by value to the function and the called function begins execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM