2017-03-07 64 views
-1

最近我在使用golang時遇到以下問題。可以將函數體傳遞給函數調用,比如javascript。 例如setTimeout(function(i){console.log("input:", i)}, 1000).將函數體/定義作爲參數傳遞給golang中的函數調用

在javascript中將匿名函數傳遞給另一個函數是很常見的。我想知道是否一樣?

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") 
} 

他們都有效,但我想知道這兩種用法是否有區別,哪一種更可取?

+2

您沒有在代碼中傳遞函數,只是將函數值存儲在局部變量中,然後調用它。看到這個相關的問題:[頭等功能在Go](http://stackoverflow.com/questions/4358031/first-class-functions-in-go) – icza

+1

它沒有區別。 – Nadh

+0

謝謝@icza。我覺得應該沒什麼區別,我的一個同事似乎認爲不是。我很好奇的是,我無法在第二種風格中找到任何代碼在線編寫,而在Javascript中很常見(我幾周前從Javascript切換到Golang)。此外,在Golang的規範中沒有提到堆和棧,它看起來Golang足夠聰明,可以動態地分配內存,以便用戶不會像c/C++一樣關心內存泄漏。我對嗎? –

回答

1

沒有什麼區別,請使用更適合您風格的設計。

相關問題