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
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e843b9-cc5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e843b9-cc5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?