将参数传递给Go IIFE(以下javascript示例) [英] Passing argument to Go IIFE (following javascript example)

查看:52
本文介绍了将参数传递给Go IIFE(以下javascript示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于使用javascript编程,可以执行以下操作以将参数传递给立即调用的函数表达式:

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);

因此,我希望能够在Go中执行类似的操作,如下所示.但是,它似乎不起作用.

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)

所以我必须这样做:

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

因此,我的问题是如何将参数传递给Go IIFE?如果不可能,为什么不呢?

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

推荐答案

Go中的函数参数需要类型.因此,请执行以下操作:

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

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

这篇关于将参数传递给Go IIFE(以下javascript示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆