xxxxxxxxxx
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Main function
func main() {
channel := make(chan string, 2)
go func() {
time.Sleep(3 * time.Second)
channel <- "Hello, Gophers!"
}()
select {
case output := <-channel:
fmt.Println(output)
case <-time.After(5 * time.Second):
fmt.Println("It's timeout..")
}
}
xxxxxxxxxx
package main
import (
"fmt"
"time"
)
func main() {
channelImmutable()
}
// -> you use only allow one channel capacity, but you use 2 capacity, channel can be blocked
// for handle this issue, you must create channel to zero value, like this <- ch
func channelImmutable() {
ch := make(chan string, 1)
ch <- "marwan"
<-ch
ch <- "jajang"
fmt.Println("channelOne", <-ch) // and i can print jajang not marwan and this can't be blocked
}
// channelOne print value, with declare to variable channel;
func channelOne() {
ch := make(chan string, 2)
ch <- "marwan"
ch <- "jajang"
fmt.Println("channelOne", <-ch)
fmt.Println("channelOne", <-ch)
}
// channelTwo print value and wrapper with gorutine, because with you use loop range not using gorutine channel is blocked, because you print more channel
func channelTwo() {
ch := make(chan string, 2)
ch <- "marwan"
ch <- "jajang"
go func() {
for v := range ch {
fmt.Println(v)
}
}()
time.Sleep(time.Second * 1)
}
// channelThree print value without gorutine, but with loop and length channel
func channelThree() {
ch := make(chan string, 2)
ch <- "marwan"
ch <- "jajang"
for i := 0; i <= len(ch); i++ {
fmt.Println(<-ch)
}
}
xxxxxxxxxx
package main
import "fmt"
func main() {
// create channel of integer type
number := make(chan int)
// access type and value of channel
fmt.Printf("Channel Type: %T\n", number)
fmt.Printf("Channel Value: %v", number)
}
xxxxxxxxxx
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}