对潜在的可变范围(可能是指针)感到困惑? 不确定

I tried searching for an answer (I feel this is a basic concept) but I was unable to find one that related directly to mine... so here is my post.

I am currently parsing log files off my server and building a script to kind of automate some of the process (learn a new skill, make my job easier, etc.). I built a simplified parser to breakdown each line. I have omitted quite a bit of code as it's unrelated.

Here is my function:

var parsedDataSet = make(map[int][]string)

func parseData(dataSet []string) {
    var tempArray []string
    for index, element := range dataSet {
        tempData := strings.Fields(element)
        tempArray = append(tempArray, tempData[0], tempData[3][1:]+" "+tempData[4][:len(tempData[4])-1], tempData[5][1:], tempData[6], tempData[7][:len(tempData[7])-1], tempData[8], tempData[9])
        parsedDataSet[index] = tempArray
        fmt.Println(parsedDataSet[index])
        tempArray = tempArray[:0]
    }
    fmt.Println("------")
    fmt.Println(parsedDataSet[0])
    fmt.Println(parsedDataSet[1])
    fmt.Println(parsedDataSet[2])
    fmt.Println(parsedDataSet[3])
}

Here is the sample result:

Sample result from a test file.

As you can see when I print out the "parsedDataSet" variable at different sections it holds different values. Above the "------" line break is the values I want, below is the values I am showing outside of the "for" loop. I am leaning towards variable scope as it's assigning the values inside the "for" loop and it's not carrying it outside of that. However, I am accessing a global variable for assignment so my assumption is that it would carry through to the global scope.

I am new to Go so I am still learning quite a bit with the language - loving it so far. I just can't wrap my head around the issue. I re-wrote this in Python (my current language) and it worked perfectly fine in a near similar manner.

Thank you in advance for your help!

A slice assignment does not perform a copy, it's just a pointer. This means that every parsedDataSet entry is the same slice.

The simplest solution is for you to move var tempArray []string inside the for loop.

For details on slices and how re-slicing works, you should read up on the details