What is the correct way to handle pointer structs in loops in Go?

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

What is the correct way to handle pointer structs in loops in Go?

问题

在这个在Go Playground上的示例中,你可以看到循环遍历一个对象列表,并将它们放入一个指针结构体数组中,结果会将相同的条目多次放入数组中。

http://play.golang.org/p/rICA21kFWL

解决这个问题的一种可能方法是创建一个新的字符串,并将循环字符串中的字符串输出到新的字符串中。不过这种方法看起来有些愚蠢。

在处理这个问题时,有没有一种惯用的正确方式?

英文:

In this example on the go playground, you can see that looping over a list of objects and putting them into an array of pointer structs ends up putting the same entry into the array multiple times.

http://play.golang.org/p/rICA21kFWL

One possible solution to the issue is to make a new string and sprint the string out of the looped string into the new string. This seems silly though.

What is the idiomatically correct way to handle this problem?

答案1

得分: 1

如果我理解正确,你只是想要一个指向原始数组中相应字符串的指针数组,你可以按照以下方式实现:

// 从一开始就选择正确的大小以避免昂贵的调整大小
o := make([]*string, len(f))

// 仅迭代索引
for i := range f {
    o[i] = &f[i].username
}

这里是修改后的Go Playground链接。

英文:

In case I understood correctly and you simply want an array of pointers pointing to the respective string in the original array, you can always do this

# choose correct size from beginning to avoid costly resize
o := make([]*string, len(f))

# iterate only over index
for i := range f {
    o[i] = &f[i].username
}

Here's your go playground with the changes sketched out above.

huangapple
  • 本文由 发表于 2014年7月12日 02:49:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/24704527.html
匿名

发表评论

匿名网友

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

确定