这段 Golang 代码有什么问题?

huangapple go评论92阅读模式
英文:

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:

http://play.golang.org/p/3gaI500Z9h

huangapple
  • 本文由 发表于 2014年2月13日 23:14:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/21758135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定