dshm8998473 2014-06-02 17:43
浏览 55
已采纳

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

The name of a function parameter in go is optional. meaning the following is legal

func hello(string) {

    fmt.Println("Hello")
}

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

(Go Playground link)

How can I refer to the 1. argument (declared with a type of string) argument in the foo() function ?

  • 写回答

1条回答 默认 最新

  • dpt1712 2014-06-02 17:52
    关注

    The only use of unnamed parameters is when you have to define a function with a specific signature. For instance, I have this example in one of my projects:

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

    And I can use both of these functions in it:

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

    Even though in the case of ExportContacts, I do not use the string parameter. In fact, without naming this parameter, I have no way of using it in this function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Fluent udf 编写问题
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500
  • ¥15 氧化掩蔽层与注入条件关系
  • ¥15 Django DRF 如何反序列化得到Python对象类型数据
  • ¥15 多数据源与Hystrix的冲突