How to pass vars with chan between functions

Issue

I’m implementing a simple mechanism of passing variable between two goroutines with a channel. Here is my code:

pipe := make(chan string)
go func(out chan string, data string) { //1st goroutine
        out <- DataSignerMd5(data)
    }(pipe, data)
go func(in chan string) {               //2nd goroutine
        data := <-in
        in <- DataSignerCrc32(data)
    }(pipe)
crcMdData := <- pipe

More likely, crcMdData pulls a variable from pipe before 2nd goroutine. I guess that I simply can create another channel to make this work. But maybe it’s possible with a single pipe?

Solution

You should use a second channel for what you want to do. You could get away with using a single channel and switching on the result, but that’s not really ideal – you’re basically trying to put two different types of objects into the same channel, and your program will end up being a lot cleaner and easier to reason about if you just have one channel per data type / intended transformation.

Answered By – Venantius

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.