How to return all value out the for loop in golang

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

How to return all value out the for loop in golang

问题

在Python中,我可以返回我在数组中添加的值:

valuesinPy = []
for i in range(len(value)):
   valuesinPy.append(value[i])
return valuesinPy

在Go语言中,可以返回我想要添加的所有值:

valueappend := make(map[string]string)
for i := range value {
    valueappend["abs"] = value[i]
}
return valueappend

它们都是相同的,但是返回的值相同,我感到困惑。

问题已解决:
我使用了map[string]interface{}{},我少了一个切片的结构。

valueappend := []map[string]interface{}{}
for i := range value {
   valueappend = append(valueappend, map[string]interface{}{
        "valueIwant append": value[i],
     })
}
return valueappend
英文:

In python I can return how value what I append in the array

valuesinPy= []
for i range(len(value)) :
   valuesinPy.append(value[i])
return valuesinPy 
  

It's able to return all value I want to append in golang

valueappend =make(map[strig]string)
for i :=range value{
    valueappend['abs']=value[i]
}
return  valueappend  

it's all same
But the value return same I got confused

Problem fix
I use the map [string]interface{}{} I less one struct of slice

valueappend:=map[string]interface{}{}
for i :=range value{
   valueappend= append(valueappend, map[string]interface{}{
        "valueIwant append" value[i] :
     }
}
return valueappend

答案1

得分: 1

我能看到的一个问题是,在循环的所有迭代中,你使用的键是相同的。

valueappend['abs']=value[i]

这将覆盖所有先前的值,最终你只会保存循环中的最后一个值。最后,你将得到一个只有一个值的映射。我猜这不是你想要的结果。你可以为每个迭代使用唯一的键,如下所示,或者使用类似的方法:

    valueappend[i]=value[i]
}```

@范纪予,请提供更多信息并澄清你在这里想要实现什么。

<details>
<summary>英文:</summary>

One issue I can see is that the key you are using is same in all iterations of the loop

valueappend['abs']=value[i]

This will overwrite all previous values and you will only have the last one in the loop be saved. In the end you will get a map with just one value. I&#39;m guessing that&#39;s not what you want here. Use can use a unique key for each iteration as follows, or something else along the same line

for i := range value {
valueappend[i]=value[i]
}


@范紀予 please add more info and clarify what you are trying to achieve here.

</details>



# 答案2
**得分**: 0

你可能需要在每次循环中更改地图的值,否则```value[i]```的每个值都将写入地图中的同一字段,导致地图中只有最后一个i的值。

<details>
<summary>英文:</summary>

You&#39;ll probably need to change the value of the map each time you go through the loop, or else every value from ```value[i]``` will keep writing to that same field in the map, leaving with the last value of i as your only value in the map

</details>



huangapple
  • 本文由 发表于 2022年5月9日 09:09:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/72166100.html
匿名

发表评论

匿名网友

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

确定