C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Func: In this example we create a func and invoke it. We use the go-keyword to call it as a goroutine.
Computation: The func uses three nested for-loops to waste some time. It does nothing important.
Chan: The func returns the value of the variable res on the channel. This can be any int value.
Then: A PrintLn statements is executed—before the computation finishes. The channel result is waited for, and then printed.
Golang program that uses chan, makes channel
package main
import "fmt"
func main() {
// Make a channel that returns an int.
c := make(chan int)
// Call this func.
go func() {
// This does a long-running numerical computation.
// ... It increments a number, then decrements it.
res := 0
for i := 0; i < 100; i++ {
for x := 0; x < 10000; x++ {
for z := 0; z < 10000; z++ {
res++
}
for z := 0; z < 10000; z++ {
res--
}
}
}
// Return the counter on the channel.
c <- res
}()
fmt.Println("HERE")
// Wait for result of func, store value in local.
res := <-c
fmt.Println("DONE")
fmt.Println("RESULT =", res)
}
Output
HERE
DONE
RESULT = 0