The problem of Golang struct, people who understand it are invited.

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.

May.20,2022

func (a *A) Clear() {
    a = &A{make([]*B, 0)}
    return
}

modify to

func (a *A) Clear() {
    a.BS = make([]*B, 0)
    return
}

in addition to the upstairs solution, you can also write:

func (a *A) Clear() {
    *a = A{make([]*B, 0)}
    return
}
Menu