donglei2288 2017-05-11 21:30
浏览 2
已采纳

Golang结构从输入获得不同的值

I am seeing weird behavior in the following code:

type A struct {
    D []int8
}

func main() {
    a := A{D: make([]int8, 0)}
    a.D = append(a.D, 0)

    b := a
    c := a
    b.D = append(b.D, 1)
    c.D = append(c.D, 2)
    fmt.Println(a.D, b.D, c.D)
}

I'm expecting output to be

[0] [0 1] [0 2]

However I got

[0] [0 2] [0 2]

Anyone know why...?

p.s. If I comment out line "a.D = append(a.D, 0)", or change the type of D from "[ ]int8" to "[ ]int", I got what I expected. Weird...

  • 写回答

1条回答 默认 最新

  • douou8954 2017-05-11 21:52
    关注

    First off, changing the type doesn't fix it: https://play.golang.org/p/fHX3JAtfNz

    What is happening here has to do with the mechanics of append and reference types.

    Basically, all three structs are pointing at the same underlying array, but each slice has its own unique length argument.

    So when you append 1 to b, it is [0 1] with a length of 2. c is still [0] with a length of 1. You then append 2 to c, making it [0 2] with a length of 2. Inadvertently, you are also changing the second value of the array in b. If you could change the length of the a without append, it would also be [0 2].

    Make sense? Pointers and slices are weird. Full story is here: https://blog.golang.org/slices

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路