scc
scc

Reputation: 10696

In go, how to create a constructor for a type without any arguments

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?

Upvotes: 0

Views: 239

Answers (3)

peterSO
peterSO

Reputation: 166569

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]]

Upvotes: 3

JimPaek
JimPaek

Reputation: 145

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.

Upvotes: 1

mna
mna

Reputation: 23963

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

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

Upvotes: 2

Related Questions