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 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格