drnycqxwz63508434 2014-02-13 15:14
浏览 48
已采纳

Golang代码有什么问题

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条回答 默认 最新

  • duangu8264 2014-02-13 16:23
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao