Weird slice of struct

89 views
Skip to first unread message

csti...@gmail.com

unread,
Dec 4, 2019, 4:55:47 PM12/4/19
to golang-nuts
Hello Golang nuts group.

I've tested golang's slice and got a weird result. 

Anyone can explain it? 

Screen Shot 2019-12-05 at 6.35.04 AM.png























Screen Shot 2019-12-05 at 6.35.42 AM.png
Why the ID of struct in the go-routine refer same address? 
Thanks.
I attach the 

Screen Shot 2019-12-05 at 6.35.04 AM.png

Ian Lance Taylor

unread,
Dec 4, 2019, 5:17:28 PM12/4/19
to csti...@gmail.com, golang-nuts
On Wed, Dec 4, 2019 at 1:55 PM <csti...@gmail.com> wrote:
Hello Golang nuts group.

I've tested golang's slice and got a weird result. 

Anyone can explain it?





On this mailing list please just send code as plain text or as a link to the Go playground.  Please don't send a picture of code.  That is much harder to read and to use.

Unfortunately I don't really understand your question.  You are passing the same pointer to the goroutine each time, so why wouldn't &a.ID be the same in each goroutine?  That's how pointers work.

Ian

Martin Schnabel

unread,
Dec 4, 2019, 7:37:50 PM12/4/19
to golan...@googlegroups.com


On 04.12.19 22:40, csti...@gmail.com wrote:
> Hello Golang nuts group.
>
> I've tested golang's slice and got a weird result.
>
> Anyone can explain it?
>

the variable ss in the for range loop is one and the same variable, with
a different value of AA for each iteration. it has only one address.
after the for loop is done the variable has the value of the last
iteration. you can declare a new variable within the block scope that
changes between iterations:

https://play.golang.org/p/UMsez9sX9xO

hope that helps
Reply all
Reply to author
Forward
0 new messages