47

I have a struct:

type ProductConstructed struct {
    Name string `json:"Name"`
    BrandMedals []string `json:"BRAND_MEDALS"`
}

When I return my object with gin:

func  contructproduct(c *gin.Context) {
    var response ProductConstructed 
    response.Name = "toto"

    c.JSON(200, response)
}

func main() {
    var err error
    if err != nil {
        panic(err)
    }
    //gin.SetMode(gin.ReleaseMode)
    r := gin.Default()
    r.POST("/constructProductGo/v1/constructProduct", contructproduct)
    r.Run(":8200") // listen and serve on 0.0.0.0:8080
}

It returns:

null

instead of:

[]

How to return an empty array?

1
  • You are using struct for response instead of array of struct so current output is accurate one. It seems from your code that you want to return only one struct at a time. So instead of handling it via empty array, handle it on null. Commented May 20, 2019 at 6:54

3 Answers 3

69

So the solution was to initialize it with :

productConstructed.BrandMedals = make([]string, 0)
Sign up to request clarification or add additional context in comments.

3 Comments

or productConstructed.BrandMedals = []string{} would do too
@Seaskyways your solution is more elegant and lisible thanks
it is 100% equivalent, just different syntax
27

Just to clarify why the solution above works:

slice1 is declared, but not defined. No variable has been assigned to it yet, it equals nil. When serialized, it will return null.

slice2 is declared and defined. It equals to an empty slice, not nil. When serialized, it will return [].

var slice1 []string  // nil slice value
slice2 := []string{} // non-nil but zero-length

json1, _ := json.Marshal(slice1)
json2, _ := json.Marshal(slice2)

fmt.Printf("%s\n", json1) // null
fmt.Printf("%s\n", json2) // []

fmt.Println(slice1 == nil) // true
fmt.Println(slice2 == nil) // false

Go playground: https://play.golang.org/p/m9YEQYpJLdj

More info: https://github.com/golang/go/wiki/CodeReviewComments#declaring-empty-slices

3 Comments

This was a nice and simple answer. I did a if len(records) == 0 { return []record{} }
That's incorrect behavior since go use default values for all vars that not a pointer. go.dev/play/p/lOl4w2FEHI0
@AndreyNikishaev slice, like map and chan "are" (to make it simple) pointers in Go.
1

To return an empty list [] use:

response.BrandMedals = []string{}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.