Home >Backend Development >Golang >optional array in structure

optional array in structure

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2024-02-05 23:15:141052browse

optional array in structure

Question content

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

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 an undefined array but I don't want this error to pop up because defaulttests can exist and sometimes it doesn't appear in the json and that's why I want to make it available Reason for selection. The if else part doesn't work either.


Correct answer


When checking whether an array is empty, it is best to use len().

if len(testbody.defaulttests) > 0 {
  ...
}

Check the zero value of defaulttests in the structure below to understand this behavior more clearly

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)
    }
}

The above is the detailed content of optional array in structure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete