如何在元帅内部省略条件结构域

There is struct of MyStruct.

type MyStruct struct {
    Code        int   `json:"Code"`
    Flags       uint8 `json:"Flags"`
    OptionField int   `json:",omitempty"`
}

Following code convert it to json.

f := MyStruct{Code:500, OptionField:41}
r, _ := json.Marshal(f)
fmt.Println(string(r)

I need to "OptionField" be optional. Some time it should exist in json with one of values [0, 1, 2, 3, ]. and in the other time it should exclude from json.

My problem is: omitempty will exclude it when the value is zero, and the default value of int is zero. Is there any way to omit field in condition (ex: omit if value is -1). Or there is any way to do it.

You could use *int instead of int and set the pointer value to nil in order to omit this.

package main

import (
    "encoding/json"
    "fmt"
)

type MyStruct struct {
    Code        int   `json:"Code"`
    Flags       uint8 `json:"Flags"`
    OptionField *int  `json:",omitempty"`
}

func format(s MyStruct) string {
    r, _ := json.Marshal(s)
    return string(r)
}

func main() {
    f := MyStruct{Code: 500, Flags: 10, OptionField: new(int)}
    fmt.Println(format(f)) // {"Code":500,"Flags":10,"OptionField":0}
    f.OptionField = nil
    fmt.Println(format(f)) // {"Code":500,"Flags":10}
}