首页 > 解决方案 > Golang 参数函数

问题描述

我正在尝试使用以下链接中描述的 Go 参数函数 友好 API 的功能选项- 但是我收到一个类型错误,我不知道为什么。

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

示例代码在这里

错误信息是:

prog.go:35:18: 在 NewServer 的参数中不能使用端口(类型 func(*Server))作为类型 func(*Server) 错误

标签: goparameter-passingvariadic-functionsoptional-parameters

解决方案


正如 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


推荐阅读