Golang中的匿名函数

I'm new to the go language and functional programming.

My question is: but can you enumerate the benefits of anonymous functions in golang. I understand from this site that anonymous functions are "segments code which will only need to get run once and doesn’t need to be referenced." but I can't find the benefit from them.

A function literal represents an anonymous function. The specification mentions the primary benefit of function literals:

Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

Here are some examples uses of anonymous functions: sort.Slice, http mux.HandleFunc, panic recovery, goroutines, filepath.Walk, ast.Inspect.

The specific use case for function literals that are not stored in a variable and executed immediately is creating a new function scope to run defer in.

As an example, if you use sync.Mutex (which in a lot of cases should be replaced by channels, but that's another topic) you can scope a piece of code that needs a certain mutex locked down and still use defered unlock without keeping the mutex locked during the entire function run.

You can also defer the anonymous function if you don't want to run it immediately. This is often used with recover to handle panics within the function call.

An example from the Go documentation for net/http.

Here's a simple web server handling the path /hello:

package main

import (
  "io"
  "net/http"
  "log"
)

// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
  io.WriteString(w, "hello, world!
")
}

func main() {
  http.HandleFunc("/hello", HelloServer)
  log.Fatal(http.ListenAndServe(":12345", nil))
}

Do you notice that the function HelloServer is defined only to be passed to the call to http.HandleFunc on the first line of main? Using an anonymous function this could instead be written:

package main

import (
  "io"
  "net/http"
  "log"
)

func main() {
  http.HandleFunc("/hello", func (w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "hello, world!
")
  })

  log.Fatal(http.ListenAndServe(":12345", nil))
}

When a function only needs to be used at one place, it might be a good idea to use an anonymous function, especially when its body is small.