由于“过滤器”字段中的切片类型没有名称,因此在初始化时必须重复定义:
package mainimport "fmt"type ReportDefinition struct { Filters []struct { Column struct { ColumnName string `json:"columnName"` Value string `json:"value"` } `json:"column"` Operator string `json:"operator"` } `json:"filters"`}func main() { var rd ReportDefinition rd.Filters = append(rd.Filters, struct { Column struct { ColumnName string `json:"columnName"` Value string `json:"value"` } `json:"column"` Operator string `json:"operator"` }{ Column: struct { ColumnName string `json:"columnName"` Value string `json:"value"` }{ ColumnName: "foo", Value: "bar", }, Operator: "==", }) fmt.Printf("+%vn", rd)}
应当清楚的是,这非常不方便,因此您应该给类型名称(至少要初始化的名称):
package mainimport "fmt"type ReportDefinition struct { Filters []Filter `json:"filters"`}type Filter struct { Column Column `json:"column"` Operator string `json:"operator"`}func NewFilter(col, op, val string) Filter { return Filter{ Column: Column{ ColumnName: col, Value: val, }, Operator: op, }}type Column struct { ColumnName string `json:"columnName"` Value string `json:"value"`}func main() { var rd ReportDefinition rd.Filters = append(rd.Filters, NewFilter("foo", "==", "bar")) fmt.Printf("+%vn", rd)}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)