Passing argument to Go IIFE (following javascript example)

試著忘記壹切 提交于 2020-08-11 22:22:41

问题


I'm used to programming in javascript where I can do the following to pass an argument into an immediately-invoked function expression:

(function(twoSeconds) {
    // do something with "twoSeconds" here
})(2 * 1000);

So I expected to be able to do something similar in Go, as below. However, it doesn't seem to work.

func (twoSeconds) {
    // build error: "twoSeconds" undefined
}(time.Second * 2)

So I have to do this instead:

func () {
    twoSeconds := time.Second * 2
}()

Therefore, my question is how can I pass an argument into a Go IIFE? And if it's not possible, why not?


回答1:


Function arguments in Go need types. So do the following:

func(twoSeconds time.Duration) {
    // use twoSeconds
}(time.Second * 2)


来源:https://stackoverflow.com/questions/40081996/passing-argument-to-go-iife-following-javascript-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!