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

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

报告相同问题?

悬赏问题

  • ¥15 UltraScale 系列 Bitslip 技术支持
  • ¥15 一个线程在sleep的时候set一个信号会起作用吗
  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件