【问题标题】:Golang Parametric FunctionsGolang 参数函数
【发布时间】:2018-06-20 23:23:02
【问题描述】:

我正在尝试使用以下链接中描述的 Go 参数函数 Functional options for friendly APIs - 但是我收到一个类型错误,我不知道为什么。

我在这里添加我的代码供您查看:

Sample Code Here

错误信息是:

prog.go:35:18: cannot use port (type func(*Server)) as type func(*Server) 错误在 NewServer 的参数中

【问题讨论】:

  • 我不确定什么是“参数函数”,但你的签名不匹配 -- "func(*Server)" != "func(*Server) error"
  • 感谢 JimB。我有带有可选参数的函数——我在网上找到了这篇文章,这是一个很好的方法。我已将链接添加到我的帖子中。

标签: go parameter-passing variadic-functions optional-parameters


【解决方案1】:

正如 JimB 所指出的,签名需要完全匹配,包括返回值。在您的示例代码中,要么有端口返回错误,例如:

port := func(srv *Server) error {
    srv.Port = 8080
    return nil
}

https://play.golang.org/p/LYb846jBD-m

或者从NewServer的定义中删除错误:

func NewServer(name string, options ...func(srv *Server)) *Server

https://play.golang.org/p/4PGN3TRkBpq

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2018-11-06
    相关资源
    最近更新 更多