英文:
what's wrong with the golang code
问题
我想要对Pair进行去重并计算其频率。
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()
}
它打印出:
[{{1 1} 1} {{1 1} 1}]
[{{1 1} 2}]
[{{1 1} 2} {{1 1} 1}]
但我认为应该是:
[{{1 1} 1} {{1 1} 1}]
[{{1 1} 2}]
[{{1 1} 2}]
为什么 pss[0]
变成了 [{{1 1} 2} {{1 1} 1}]
?
英文:
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}]
?
答案1
得分: 8
你没有传递一个指向 func weed(ps PairSlice)
的指针。然后,在追加循环中创建一个新的切片时,你是在追加到另一个切片而不是修改第一个切片。
稍微修改了你的代码,我认为现在它按预期工作:
http://play.golang.org/p/3gaI500Z9h
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论