Home  >  Article  >  Backend Development  >  Attach to pointer slice

Attach to pointer slice

WBOY
WBOYforward
2024-02-06 10:00:071053browse

Attach to pointer slice

Question content

go is my first programming language and I'm trying to learn pointers by writing a program that organizes information based on taxonomies. I'm having some difficulty understanding how to attach to a pointer slice.

type list struct {
    taxonomies []taxonomy
}

func (l *list) add(t taxonomy) {
    var exists bool
    var existing *taxonomy
    for _, taxonomy := range l.taxonomies {
        if taxonomy.name == t.name {
            exists = true
            existing = &taxonomy
        }
    }
    if exists {
        for _, term := range t.data {
            termexists := false
            for _, existingterm := range existing.data {
                if existingterm.name == term.name {
                    termexists = true
                    break
                }
            }
            if termexists {
                continue
            }
            (*existing).data = append((*existing).data, term)
        }
    } else {
        l.taxonomies = append(l.taxonomies, t)
    }
}

type taxonomy struct {
    name string
    data []term
}

type term struct {
    name, link string
}

I think the problem is at the bottom, this line:

(*existing).Data = append((*existing).Data, term)

By tracing the code in the debugger, I can see that when the append occurs, the taxonomy stored in the "existing" variable is being updated, but the data in the actual list is not.

Can anyone tell me where I'm going wrong?


The correct answer


##l.taxonomies is []taxonomy, so the taxonomy value will be is a copy of the element, changes to the copy will not be reflected in the original list value.

You can iterate using an index to avoid copying values

for i := range l.taxonomies {
    if l.taxonomies[i].name == t.name {
        exists = true
        existing = &l.taxonomies[i]
    }
}

However, data passed to methods such as

append can still be copied. Instead, it's better to use pointers throughout:

type List struct {
    Taxonomies []*Taxonomy
}

func (l *List) Add(t *Taxonomy) {
...

The above is the detailed content of Attach to pointer slice. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete