```
/*
我想实现的是一个servers数组,里面装了server(map),server不同的key对应不同的value,如server1{"name":"machine1" ...},server2{"name":"machine2"}...
然后我通过遍历数组servers,遇到不同的下标时修改对应servers[i]的某个key对应的值,但是这样写下来运行每个server全都改成了同样的值,自己调试发现代码到那一步(断点)就是直接就全部server都改了,新手看了半天很困惑,希望了解的帮我看一下,先谢谢了!
*/
package main
import (
"fmt"
"strconv"
)
func main() {
servers := New()
Mod(servers)
fmt.Println(servers)
}
func New() *[]map[string]string {
server := make(map[string]string)
servers := make([]map[string]string, 0)
for i := 0; i < 5; i++ {
server["name"] = "server" + string(i)
server["type"] = "machine"
servers = append(servers, server)
}
return &servers
}
func Mod(servers *[]map[string]string) {
for i, server := range *servers {
if i == 1 {
fmt.Println(i)
server["name"] = "machine" + strconv.Itoa(i)
server["type"] = "cloud"
fmt.Println(server["name"])
}
if i == 3 {
//fmt.Println(i)
/*断点*/server["name"] = "machine" + strconv.Itoa(i)
server["type"] = "physic"
fmt.Println(server["name"])
}
}
}
```
更多评论
servers = append(servers, server)
这个数组里面的元素都是同一个server,所以你修改都是修改同一个
server你要在循环里每次都make出来
#1
func New() *[]map[string]string {
servers := make([]map[string]string, 0)
for i := 0; i < 5; i++ {
server := make(map[string]string)
server["name"] = "server" + string(i)
server["type"] = "machine"
servers = append(servers, server)
}
return &servers
}
#2