简体   繁体   中英

what's wrong with the golang code

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}] ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM