Attach to pointer slice

WBOY
Release: 2024-02-06 10:00:07
forward
1053 people have browsed it

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
}
Copy after login

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

(*existing).Data = append((*existing).Data, term)
Copy after login

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]
    }
}
Copy after login

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) {
...
Copy after login

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

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!