Home > Backend Development > Golang > optional array in structure

optional array in structure

WBOY
Release: 2024-02-05 23:15:14
forward
1004 people have browsed it

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"`
}
Copy after login
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,
        })
    }

    ...
}
Copy after login

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 {
  ...
}
Copy after login

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)
    }
}
Copy after login

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

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template