has the following code:
type B struct {
Id int `json:"id"`
Name string `json:"name"`
}
type A struct {
Bs []*B
}
func New() *A {
return &A{
Bs: make([]*B, 0),
}
}
func (a *A) Read() {
a.Bs = append(a.Bs, &B{
Id: 1,
Name: "xingyys",
})
}
func (a *A) Clear() {
a = &A{make([]*B, 0)}
return
}
func main() {
a := New()
a.Read()
a.Clear()
a.Read()
a.Clear()
a.Read()
b, _ := json.MarshalIndent(a, " ", " ")
fmt.Println(string(b))
}
the expected output should be:
{
"Bs": [
{
"id": 1,
"name": "xingyys"
}
]
}
the result is:
{
"Bs": [
{
"id": 1,
"name": "xingyys"
},
{
"id": 1,
"name": "xingyys"
},
{
"id": 1,
"name": "xingyys"
}
]
}
what is the reason for this? Ask for an answer.