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

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

问题描述:

Given this type

type Response map[string]interface{}

I created a method NewResponse which fills in the default values:

 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
}

which i call like NewResponse() but I would like to do Response.New() instead, so the method signature should be like this

func (Response) New() Response {

but then I always get the error not enough arguments in call to Response.New.

So, how could this be implemented?

给出此类型 p>

  type响应图[string]接口 {} 
  code>  pre> 
 
 

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

  func NewResponse()响应 {
 resp:=响应{“状态”:200,“ msg”:“已将作业添加到队列”} 
 
 resp_metadata:= make(map [string] string)
 resp_metadata [“ base”] =“  api / v1“ 
 resp_metadata [” self“] =” / crawler / jobs / add“ 
 resp [” metadata“] = resp_metadata 
返回resp 
} 
  code>  pre> 
  
 

我称之为 NewResponse() code>,但是我想做 Response.New() code>,所以方法签名应该像这样 p >

  func(响应)New()响应{
  code>  pre> 
 
 

,但是我总是收到错误参数不足 在对Response.New code>的调用中。 p>

那么,如何实现呢? p> div>

Although it is definitely not idiomatic Go, you could do something like this:

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
", k, v)
  }
}

But really, there's nothing wrong with func NewResponse() Response.

It doesn't. Go doesn't have constructors. To create an "empty" object is to create a zero value of the type of the object.

What you're trying to do is a Response method named New to be called on an existing Response object that would return a (different) Response object.

resp := Response{} or resp := make(Response) is fine if you need to create an empty Response.

When you write Go programs, use idiomatic Go. Then, other people will be able to read your programs. For example,

package main

import "fmt"

type Response map[string]interface{}

func NewResponse() Response {
    metadata := map[string]string{
        "base": "api/v1",
        "self": "/crawler/jobs/add",
    }
    r := Response{
        "status":   200,
        "msg":      "Added jobs to queue",
        "metadata": metadata,
    }
    return r
}

func main() {
    resp := NewResponse()
    fmt.Println(resp)
}

Output:

map[status:200 msg:Added jobs to queue metadata:map[base:api/v1 self:/crawler/jobs/add]]