我正在开展一个项目,我正在使用GO,但我遇到了一个小障碍。我将把代码放在下面,然后解释我在哪里理解正在发生的事情:
package main
import (
"fmt"
)
type Population struct {
cellNumber map[int]Cell
}
type Cell struct {
cellState string
cellRate int
}
var (
envMap map[int]Population
stemPopulation Population
taPopulation Population
)
func main() {
envSetup := make(map[string]int)
envSetup["SC"] = 1
envSetup["TA"] = 1
initialiseEnvironment(envSetup)
}
func initialiseEnvironment(envSetup map[string]int) {
cellMap := make(map[int]Cell)
for cellType := range envSetup {
switch cellType {
case "SC":
{
for i := 0; i <= envSetup[cellType]; i++ {
cellMap[i] = Cell{"active", 1}
}
stemPopulation = Population{cellMap}
}
case "TA":
{
for i := 0; i <= envSetup[cellType]; i++ {
cellMap[i] = Cell{"juvenille", 2}
}
taPopulation = Population{cellMap}
}
default:
fmt.Println("Default case does nothing!")
}
fmt.Println("The Stem Cell Population: \n", stemPopulation)
fmt.Println("The TA Cell Population: \n", taPopulation)
fmt.Println("\n")
}
}
我遇到的问题是,当我们到达switch语句中的“TA”情况时, taPopulation 的内容会被 taPopulation 覆盖。< / p>
我明确地将print语句放在for循环中以查看发生了什么:
For-loop Step1:
The Stem Cell Population:
{map[0:{active 1} 1:{active 1}]}
The TA Cell Population:
{map[]}
For循环Step2:
The Stem Cell Population:
{map[0:{juvenille 2} 1:{juvenille 2}]}
The TA Cell Population:
{map[0:{juvenille 2} 1:{juvenille 2}]}
我期待的是:
For-loop Step1:
The Stem Cell Population:
{map[0:{active 1} 1:{active 1}]}
The TA Cell Population:
{map[]}
For循环Step2:
The Stem Cell Population:
{map[0:{active 1} 1:{active 1}]}
The TA Cell Population:
{map[0:{juvenile 2} 1:{juvenile 2}]}
有人能帮我理解发生了什么以及发生了什么吗?是因为我在开始时声明的全局变量?或者这是我犯的代码错误?
答案 0 :(得分:3)
这两个结构共享相同的cellMap
。将cellMap的创建移动到循环中,您的代码将起作用。