簡體   English   中英

在 go 函數中將函數作為參數傳遞

[英]Pass a function as a parameter in go function

我想在 go 函數中傳遞一個函數作為參數。 這是我的代碼:

func Call(path string, method func()) {
    // TODO launch the method here
}

當我想調用這個函數時,我想這樣做:

func routes() {
    app.Call("/", controllers.Index())
}

Index()方法是:

func Index(res http.ResponseWriter, req http.Request) {
    userAgent := req.Header.Get("User-Agent")
    fmt.Fprintf(res, "You're User-Agent is %s", userAgent)
}

創建一個type並將這個type作為參數傳遞是個好主意嗎?

如果您創建命名類型,這完全取決於您。 從技術上講,即使您在簽名中匿名地定義類型(類型為func()在您的代碼中)。 是否需要使用名稱定義它取決於您,並取決於您的用例和需求。

無論是否定義命名類型,函數簽名都必須匹配(不能將func(http.ResponseWriter, http.Request)傳遞給func()參數),並且必須傳遞函數而不是調用它並傳遞其返回值(它沒有):

// Correct arguments required
func Call(path string, method func(http.ResponseWriter, http.Request)) {
    // TODO launch the method here
}

func routes() {
     // Index() calls the function, you just want to pass a reference to it
    app.Call("/", controllers.Index)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM