How to collect values from a channel into a slice in Go? (I want a utility method, maybe from go-funk)

Does go-funk have anything to collect values from a channel into a slice in Go? Any library that has ?

I do not want to implement this myself-

Why do you not want to implement this yourself? It seems you could just do this:

func readEverythingFromChannel(ch chan *Something) []*Something {
    somethings := make([]*Something)
    for s := range ch {
        somethings = append(somethings, s)
    }
    return somethings
}

Hi @skillian

why write 7 more lines into a file, every time you need to solve the same problem ? Is there a library that already does this ?

I guess we all have different opinions. From my perspective, the question would be “why depend on a library when I can write seven lines?”

Not to get into an argument, but considering that in @heidi’s last post, they said:

I think it might be relevant to quote one of the Go proverbs: “A little copying is better than a little dependency”.

That being said, I am not aware of any library that does this, but some of the projects that aim to make Go more functional might accept a PR. In Go 1.18 and later, you could create your own package and put a generic version of the code I put above and then reference it from your other projects so that you don’t have to write it again.

3 Likes

@skillian

There are pros and cons to both options. I think this is a spot where each developer, or team decides on its own on a case by case situation.

Anyways, what is the solution ? I had hopes for go-funk but indeed it seems that it cannot do this.

Is the author of go-funk reading this forum ? I could lend you a hand.

Go-funk couldn’t work for channels because what you want is unpredictable by design. Which channel did you pass? How you prevent channel blocks ? The external context matters here. From what I see go-funk is a group of standalone functions which do exactly what a functional language does with pipe operator , declarative style.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.