追加到指针切片

huangapple go评论78阅读模式
英文:

Appending to pointer slice

问题

Go是我的第一种编程语言,我正在尝试通过编写一个根据分类法组织信息的程序来学习指针。我在理解如何向指针切片追加元素方面遇到了一些困难。

我认为问题出在代码的最后这一行:

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

通过在调试器中跟踪代码,我可以看到在追加发生时,存储在"existing"变量中的分类法被更新了,但实际的List中的数据没有被更新。

有人能告诉我我错在哪里吗?

英文:

Go is my first programming language and I am trying to learn about pointers by writing a program that organizes information based on taxonomies. I'm having some trouble understanding how to append 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 toward the bottom, this line:

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

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

Can anyone tell me where I am going wrong?

答案1

得分: 1

l.Taxonomies 是一个 []Taxonomy,所以 taxonomy 的值将是元素的副本,对该副本的更改不会反映在原始的 List 值中。

你可以使用索引进行迭代,以避免复制该值

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

然而,这仍然存在将数据复制到像 Append 这样的方法中的可能性。相反,最好在整个过程中使用指针:

type List struct {
	Taxonomies []*Taxonomy
}

func (l *List) Add(t *Taxonomy) {
...
英文:

l.Taxonomies is a []Taxonomy, so the taxonomy value is going to be a copy of the element, and changes to that copy will not be reflected in the original List value.

You can iterate using the index to avoid copying the value

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

However that still leaves the possibility of copying the data passed to methods like Append. Instead it's probably better to use pointers throughout:

type List struct {
	Taxonomies []*Taxonomy
}

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

huangapple
  • 本文由 发表于 2023年2月7日 02:25:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定