Domanda

I'm working on a project and I am using GO, but I have hit a small obstacle. I will put the code below and then explain where I'm having trouble understanding what is happening:

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")
    }
}

The issue that I'm having is that the content of stemPopulation is being overwritten by taPopulation when we arrive at the "TA" case in the switch statement.

I explicitly put the print statements in the for loop to see what is going on:

For-loop Step1:

The Stem Cell Population: 
 {map[0:{active 1} 1:{active 1}]}
The TA Cell Population: 
 {map[]}

For-loop Step2:

The Stem Cell Population: 
 {map[0:{juvenille 2} 1:{juvenille 2}]}
The TA Cell Population: 
 {map[0:{juvenille 2} 1:{juvenille 2}]}

What I am expecting:

For-loop Step1:

The Stem Cell Population: 
 {map[0:{active 1} 1:{active 1}]}
The TA Cell Population: 
 {map[]}

For-loop Step2:

The Stem Cell Population: 
 {map[0:{active 1} 1:{active 1}]}

The TA Cell Population: 
 {map[0:{juvenile 2} 1:{juvenile 2}]}

Could anybody help me understand what is going on and why it is happening ? Is it because of the global variables that I declared at the beginning? or is it a code error that I made?

È stato utile?

Soluzione

The two structures share the same cellMap. Move the creation of cellMap into the loop and your code will work.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top