Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing argument to Go IIFE (following javascript example)

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?

like image 366
user162097 Avatar asked Oct 20 '25 14:10

user162097


1 Answers

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

func(twoSeconds time.Duration) {
    // use twoSeconds
}(time.Second * 2)
like image 86
abhink Avatar answered Oct 23 '25 04:10

abhink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!