如何在go中引用一个未命名的函数参数?

时间:2014-06-02 17:43:29

标签: go

go中函数参数的名称是可选的。意思是以下是合法的

func hello(string) {

    fmt.Println("Hello")
}

func main() {
    hello("there")
}

Go Playground link

如何引用1.参数(用一种字符串声明)参数 foo()函数?

1 个答案:

答案 0 :(得分:6)

未命名参数的唯一用途是必须定义具有特定签名的函数。例如,我在我的一个项目中有这个例子:

type export struct {
    f func(time.Time, time.Time, string) (interface{}, error)
    folder    string
}

我可以在其中使用这两个功能:

func ExportEvents(from, to time.Time, name string) (interface{}, error)
func ExportContacts(from, to time.Time, _ string) (interface{}, error)

即使在ExportContacts的情况下,我也不使用string参数。事实上,如果没有命名这个参数,我就无法在这个函数中使用它。