0
我正在開發一個項目,我正在使用GO,但我碰到了一個小障礙。我會把下面的代碼,然後解釋在那裏我無法理解發生了什麼事:在switch語句中覆蓋地圖
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")
}
}
是我遇到的問題是,stemPopulation的內容受到taPopulation覆蓋時我們到達switch語句中的「TA」情況。
我明確地把打印語句在for循環,看看到底是怎麼回事:
for循環第一步:
The Stem Cell Population:
{map[0:{active 1} 1:{active 1}]}
The TA Cell Population:
{map[]}
for循環第二步:
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循環第二步:
The Stem Cell Population:
{map[0:{active 1} 1:{active 1}]}
The TA Cell Population:
{map[0:{juvenile 2} 1:{juvenile 2}]}
任何人可以幫助我瞭解是怎麼回事,爲什麼它是怎麼回事?是因爲我在開始時聲明瞭全局變量嗎?或者它是我犯的一個代碼錯誤?
謝謝!現在我覺得這很有道理......我應該更加小心。 – sSmacKk