Home > OS >  Optional array in struct
Optional array in struct

Time:12-20

I want to make an array optional in struct and use it with an if else in a func.

type TestValues struct {
    Test1 string `json:"test1"`
    DefaultTests []string `json:"__tests"`

    //DefaultTests *array `json:"__tests,omitempty" validate:"option"`
    Test2 string `json:"__Test2"`
}
func (x *Controller) createTest(context *gin.Context, uniqueId string, testBody *TestValues) (*http.Response, error) {

    if testBody.DefaultTags {
        postBody, err := json.Marshal(map[string]string{
            "Test2":              testBody.Test2,
            "Test1":                  testBody.Test1,
            "defaultTests":         testBody.DefaultTests,
            "uniqueId":                  uniqueId,
        })
    } else {
        postBody, err := json.Marshal(map[string]string{
            "Test2":              testBody.Test2,
            "Test1":                  testBody.Test1,
            "uniqueId":                  uniqueId,
        })
    }

    ...
}

When I run the code it tells me that DefaultTests is undefined array but I don't want this error to pop because DefaultTests can existe and sometimes it won't be present in the json that's why I want to make it optional. The if else part is not working too.

CodePudding user response:

It's better to use len() when checking if an array is empty here.

if len(testBody.DefaultTests) > 0 {
  ...
}

Check the Zero value of the DefaultTests in struct below for more clarity on this behaviour

package main

import "fmt"

type TestValues struct {
    Test1        string   `json:"test1"`
    DefaultTests []string `json:"__tests"`

    //DefaultTests *array `json:"__tests,omitempty" validate:"option"`
    Test2 string `json:"__Test2"`
}

func main() {
    var tv = TestValues{Test1: "test"}

    if len(tv.DefaultTests) > 0 {
        fmt.Printf("Default Tests: %v\n", tv.DefaultTests)
    } else {
        fmt.Printf("Default Tests empty value: %v\n", tv.DefaultTests)
    }
}

CodePudding user response:

Here's my final code with Marc's answer

func (x *Controller) createTest(context *gin.Context, uniqueId string, testBody *TestValues) (*http.Response, error) {

if len(testBody.DefaultTags) > 0 {
  postBody, err := json.Marshal(testBody.DefaultTags)

} else {
    postBody, err := json.Marshal(map[string]string{
        "Test2":              testBody.Test2,
        "Test1":                  testBody.Test1,
        "uniqueId":                  uniqueId,
    })
}

...

}

  •  Tags:  
  • go
  • Related