FAQ
foo is a var at a fixed address space that is used multiple times. Since
you are saving that address, the last value of foo at that address is 3.
https://play.golang.org/p/2nHctYB6ML
On Saturday, January 30, 2016 at 8:36:21 AM UTC-8, Simone Carletti wrote:

Hello,

I was investigating a bug in a library, and I narrowed down the problem
with a simple reproducible example. Although I found the cause of the
issue, I can't understand why the following code is behaving in this way
https://play.golang.org/p/_8XNo-7iKy

type Foo struct {
Name string
}

func main() {
foos := []Foo{Foo{Name:"1"}, Foo{Name:"2"}, Foo{Name:"3"}}
var pFoos []*Foo
for _, foo := range foos {
if foo.Name == "2" {
pFoos = append(pFoos, &foo)
}
}

fmt.Println(pFoos)
fmt.Println(*pFoos[0]) // prints {3} instead of {2}

bars := []*Foo{&Foo{Name:"a"}, &Foo{Name:"b"}, &Foo{Name:"c"}}

var pBars []*Foo
for _, bar := range bars {
if bar.Name == "b" {
pBars = append(pBars, bar)
}
}

fmt.Println(pBars)
fmt.Println(*pBars[0]) // prints {b} as expected
}

Specifically, when I "filter" the array of pointers, the final array
always contains a pointer to the last element in the original array
(instead of the matched one). Instead, when I "filter" the array of
Structs, then I get the correct result.

Can someone help me to understand what's going on behind the scenes here?

Thanks,
-- Simone
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 of 8 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJan 30, '16 at 4:36p
activeFeb 3, '16 at 2:02p
posts8
users5
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase