Return empty list instead of null

后端 未结 2 1364
南旧
南旧 2021-01-07 12:58

I want to change my current function to return empty JSON list, currently it returns nil.

This is my current code:

func (s *Service) pro         


        
2条回答
  •  广开言路
    2021-01-07 13:50

    Another way to handle this is to check if the slice is nil and initialize it:

    projects = ps
    if projects == nil {
        projects = make([]*models.Project, 0)
    }
    

    This can be tedious if you have several structs and structs with arrays. To handle those, you can create custom marshalers or dynamically inspect fields.

    Source: Arrays and JSON in Go

提交回复
热议问题