doupafu6980 2017-12-08 14:06
浏览 4
已采纳

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

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!

  • 写回答

1条回答 默认 最新

  • douzhe9927 2017-12-08 14:11
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改