Golang中的匿名函数

问题描述 投票:-1回答:3

我是go语言和函数式编程的新手。

我的问题是:但你可以列举golang中匿名函数的好处。我从这个site了解到,匿名函数是“段代码,只需要运行一次而不需要引用”。但我找不到他们的好处。

go
3个回答
3
投票

函数文字表示匿名函数。 specification mentions the primary benefit of function literals

函数文字是闭包:它们可以引用周围函数中定义的变量。然后,这些变量在周围函数和函数文本之间共享,只要它们可访问,它们就会存在。

以下是一些匿名函数的使用示例:sort.Slicehttp mux.HandleFuncpanic recoverygoroutinesfilepath.Walkast.Inspect


1
投票

来自Go documentation for net/http的一个例子。

这是一个处理路径/hello的简单Web服务器:

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!\n")
}

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

你是否注意到函数HelloServer只被定义为传递给http.HandleFunc第一行的main调用?使用匿名函数可以改为:

package main

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

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

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

当一个函数只需要在一个地方使用时,使用匿名函数可能是个好主意,特别是当它的主体很小时。


0
投票

函数文字的特定用例没有存储在变量中并立即执行,它创建了一个新的函数范围来运行defer

例如,如果您使用sync.Mutex(在很多情况下应该用通道替换,但这是另一个主题),您可以调整一段需要锁定某个互斥锁的代码并仍使用延迟解锁而不保持互斥锁定在整个功能运行期间。

如果您不想立即运行,也可以推迟匿名函数。这通常与recover一起用于处理函数调用中的恐慌。

© www.soinside.com 2019 - 2024. All rights reserved.