I am trying to figure out how to make concurrent the forward Swap function in Go for learning concepts purpose:
package main
import "fmt"
func Swap(a, b int) (int, int) {
return b, a
}
func main() {
for i := 0; i <10; i++ {
fmt.Println(Swap(i+1, i))
}
}
So far I have came up with this solution:
package main
import "fmt"
// Only Send Channel
func Swap(a, b chan<- int) {
go func() {
for i := 0; i < 10; i++ {
a <- i + 1
b <- i
}
}()
}
func main() {
a := make(chan int)
b := make(chan int)
Swap(a, b)
for i := 0; i < 10; i++ {
fmt.Printf("chan a received: %d | chan b received: %d\n", <-a, <-b)
}
}
It seems to work but I cannot be sure about it. How can I measure this and does anyone knows how to really make a simple Swap function concurrent in Go?