Reputation: 1383
i want to weed Pair and count its' frequency
package main
import (
"fmt"
)
type Pair struct {
a int
b int
}
type PairAndFreq struct {
Pair
Freq int
}
type PairSlice []PairAndFreq
type PairSliceSlice []PairSlice
func (pss PairSliceSlice) Weed() {
fmt.Println(pss[0])
weed(pss[0])
fmt.Println(pss[0])
}
func weed(ps PairSlice) {
m := make(map[Pair]int)
for _, v := range ps {
m[v.Pair]++
}
ps = ps[:0]
for k, v := range m {
ps = append(ps, PairAndFreq{k, v})
}
fmt.Println(ps)
}
func main() {
pss := make(PairSliceSlice, 12)
pss[0] = PairSlice{PairAndFreq{Pair{1, 1}, 1}, PairAndFreq{Pair{1, 1}, 1}}
pss.Weed()
}
it prints
[{{1 1} 1} {{1 1} 1}]
[{{1 1} 2}]
[{{1 1} 2} {{1 1} 1}]
but i thought it should be
[{{1 1} 1} {{1 1} 1}]
[{{1 1} 2}]
[{{1 1} 2}]
why does pss[0]
turn to [{{1 1} 2} {{1 1} 1}]
?
Upvotes: 2
Views: 190
Reputation: 49187
You are not passing a pointer to func weed(ps PairSlice)
. Then when you create a new slice in the append loop, you are appending to another slice and not modifying the first one.
Changed your code slightly and I think it works as expected now:
http://play.golang.org/p/3gaI500Z9h
Upvotes: 8