function - 将函数体/定义作为参数传递给 golang 中的函数调用

标签 function go parameter-passing

最近在使用golang的过程中遇到了如下问题。将函数体传递给函数调用是否可以,例如 javascript。 例如setTimeout(function(i){console.log("input:", i)}, 1000).

在 javascript 中将匿名函数传递给另一个函数是很常见的。我想知道在 go 中是否相同?

package main

import (
    "fmt"
)

type HandlerFunc func(int)

func main() {
    // define a function as object/variable?
    hnd := func(in int){
        fmt.Println("func handler returns input", in);
    }
    a:=HandlerFunc(hnd) //pass function object/variable to type HandlerFunc
    a(10)

    // pass function body directly to type HandlerFunc
    b:=HandlerFunc(func(_in int){
        fmt.Println("another func handler returns input", _in);
    })
    b(100)

    fmt.Println("Hello, playground")
}

它们都有效,但我想知道这两种用法之间是否有任何区别,哪种更可取?

最佳答案

没有区别,使用更适合您风格的那个。

关于function - 将函数体/定义作为参数传递给 golang 中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42646717/

相关文章:

jquery - 为什么多个 JQuery 函数不能从代码隐藏中调用

google-app-engine - Google Datastore 在 Golang 中嵌套实体

go - 在 Golang 中使用库

ios - 方法和参数声明?

scheme - 将值绑定(bind)到环境模型中的帧

javascript - 从函数返回值作为jQuery中参数的值

function - Julia 模块调用用户定义函数

C++ 函数不会执行多次

go - 如何在 Golang 中将 vars 传递给 chi router

javafx - 传递参数JavaFX FXML