[英]Golang edit array of struts from main() to function
hoping you can help below is a concise version of my code. 希望您能在下面提供帮助,是我代码的简明版本。
basically im passing an array of structs to floatInSlice() in which either a new struct gets added to the array or an existing struct AudienceCategory.Sum gets ++ 基本上我将结构数组传递给floatInSlice(),其中将新结构添加到数组或现有结构AudienceCategory.Sum获取++
all is generally working fine except for the b.Sum = b.Sum+1 除了b.Sum = b.Sum + 1以外,其他所有工具都正常工作
Now I know that if I want to pass an obect as a pointer rather than value I need to use */& but I just cant seem to get it working, any help much appriciated! 现在我知道,如果我想将对象传递为指针而不是值,则需要使用* /&,但我似乎无法使其正常运行,任何帮助都非常有用!
type AudienceCategory struct {
Cat int
Sum int
}
var counter = []AudienceCategory{}
func main() {
for i := 1; i < len(words); i++ {
counter = floatInSlice(category,counter)
if counter != nil{}
}
fmt.Printf("%v ", counter)
}
func floatInSlice(category int, counter *[]AudienceCategory) []AudienceCategory {
for _, b := range counter {
if b.Cat == category {
b.Sum = b.Sum+1
return counter
}
}
x := AudienceCategory{Cat:category,Sum:1}
counter = append( counter, x)
return counter
}
EDIT ******* 编辑*******
got it working in the end thanks for the help guys 最后成功了,谢谢大家的帮助
func floatInSlice(category int, counter []AudienceCategory) []AudienceCategory {
for i := 0; i < len(counter); i++ {
if counter[i].Cat == category {
counter[i].Sum = counter[i].Sum+1
return counter
}
}
x := AudienceCategory{Cat:category,Sum:1}
counter = append( counter, x)
return counter
}
When you use value range as in _, b := range counter
, b
contains a copy of each element of counter
. 当使用值的范围如
_, b := range counter
, b
包含的各元素的副本counter
。 So you are summing a copy that is lost, not the element in the slice. 因此,您要对丢失的副本而不是切片中的元素求和。
You should use 你应该用
func floatInSlice(category int, counter *[]AudienceCategory) []AudienceCategory {
for i, b := range *counter {
if b.Cat == category {
(*counter)[i].Sum = (*counter)[i].Sum+1
return counter
}
}
x := AudienceCategory{Cat:category,Sum:1}
counter = append( counter, x)
return counter
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.