在使用过程中,如何为没有任何参数的类型创建构造函数

苏菲亚 :

鉴于这种类型

type Response map[string]interface{}

我创建了一个方法NewResponse,它填充了默认值:

 func NewResponse() Response {
    resp := Response{"status": 200, "msg": "Added jobs to queue"}

    resp_metadata := make(map[string]string)
    resp_metadata["base"] = "api/v1"
    resp_metadata["self"] = "/crawler/jobs/add"
    resp["metadata"] = resp_metadata
    return resp
}

我称之为,NewResponse()但我想Response.New()代替它,所以方法签名应该像这样

func (Response) New() Response {

但是然后我总是得到错误not enough arguments in call to Response.New

那么,如何实现呢?

我:

尽管绝对不是Go语言,但是您可以执行以下操作

type Response map[string]interface{}

func (r *Response) New() {
  *r = make(map[string]interface{})
  (*r)["hello"] = "World"
  (*r)["high"] = 5
}

func main() {
  var r Response
  r.New()
  for k, v := range r {
    fmt.Printf("%s = %v\n", k, v)
  }
}

但实际上,没什么错func NewResponse() Response

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用过程中丢失可变数据

Ubuntu 16.04在使用过程中冻结

如果由ScheduledAgent触发,则GetStringAsync错误,但在WP8应用程序使用过程中没有错误

如何使用可选参数创建构造函数?

当用户在Android应用程序使用过程中连接到Internet时,如何显示横幅广告?

防止或检测“ this”在使用过程中被删除

使用过程中MySQL对表达式变化的评估

无法为具有模板类型参数的模板类型创建构造函数

如何为从具有泛型的抽象类继承的类创建构造函数?

在使用过程中,如何将封闭与大猩猩/多路复用子路由器一起使用?

如何创建构造函数?

如何创建构造函数?

如何创建构造函数?

如何在JavaScript中创建构造函数以创建构造函数?

TS2351:如何在ts中为new函数创建构造函数类型

如何使用箭头函数创建构造函数

JOOQ:如何为没有参数的存储过程创建MockResult?

在Go中,如何为具有字符串基本类型的类型创建“构造函数”?

创建构造函数后使用原型有什么好处?

如何在 R 中创建构造函数?

如何在Julia中为结构创建构造函数?

在Pharo或Smalltalk中创建构造函数

是这个工厂吗?我如何为结构创建构造函数?

如何为存储过程中的 in 子句传入参数?

如何在out参数中创建可以在存储过程中传递的类型?

使用内部JSON构造函数在AutoFixture 4.8.0中创建公共类型,并带有许多构造函数参数

创建过程中如何为实例分配属性?

hibernate3中没有参数的调用过程

反射发射:如何为此构建构造函数