douao8204 2018-09-02 20:44
浏览 28
已采纳

片段结构值始终被最后一个索引覆盖

I am not able to understand the behavior of this code block. What I am doing wrong and what should be the proper way to do this?

import (
    "fmt"
    "strconv"
)

type Record struct {
    name *string
}
type person struct {
    name string
}

func main() {
    var Records []*Record
    var persons []person
    for i := 0; i < 10; i++ {
        newValue := person{name: strconv.Itoa(i)}
        persons = append(persons, newValue)
    }
    for _, personone := range persons {
        newRecord := &Record{}
        getName(newRecord, &personone)
        Records = append(Records, newRecord)
    }
    for _, record := range Records {
        fmt.Println(*record.name)
    }

}

func getName(record *Record, value *person) {
    record.name = &value.name
}

I am expecting this code to print 0 to 9, but it always prints 9, the last value.

  • 写回答

1条回答 默认 最新

  • dqst96444 2018-09-02 20:51
    关注

    for _, personone := range persons {

    in this statement personone is a variable that is declared once and is overwritten on every iteration.

    Then you obtain its address in this statement getName(newRecord, &personone).

    So you pass the same address every time, which is changed in every iteration.

    So you end up having the same value, since you have assigned the same address.

    How to fix: don't use pointers if you don't actually need them.

    A super dirty hack would be to make a copy of the structure explicitly https://play.golang.org/p/Sp4xD88rfvE

    for _, personone := range persons {
        personone := personone // <-- see here
        newRecord := &Record{}
        getName(newRecord, &personone)
        Records = append(Records, newRecord)
    }
    

    but I really would not recommend you doing that

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

报告相同问题?

悬赏问题

  • ¥20 SpringBoot+Vue3
  • ¥15 高额悬赏~绕过防火墙被针对了
  • ¥15 IT从业者的调查问卷
  • ¥65 LineageOs-21.0系统编译问题
  • ¥30 关于#c++#的问题,请各位专家解答!
  • ¥15 App的会员连续扣费
  • ¥15 不同数据类型的特征融合应该怎么做
  • ¥15 用proteus软件设计一个基于8086微处理器的简易温度计
  • ¥15 用联想小新14Pro
  • ¥15 multisim中关于74ls192n和DSWPK开关仿真图分析(减法计数器)