In my opinion,the "select...case" means "If any chan is available, it executes".So,Why are there error here ,I think message<-msg
is available chan send , but it cause deadlock!. thanks very much.
import "fmt"
func main() {
messages:=make(chan string)
//signals:=make(chan string)
select {
case msg:=<-messages:
fmt.Println(msg)
default:
fmt.Println("no mes receivedd")
}
msg:="h1"
select {
case messages<-msg:
fmt.Println("sent message",msg)
}
}
CodePudding user response:
The first select has a default
case, so it selected that immediately. The second select attempts to write to messages
, but there are no other goroutines listening, so you have a deadlock.
Move the second select before the first, put it in a goroutine, and remove the default
case, then you'll have a successful send/receive.
CodePudding user response:
source geeksforgeeks
Here we have two goroutines map with two functions. one goroutine map with main function and one with an anonymous function.
package main
import (
"fmt"
)
func main() {
messages := make(chan string)
//signals:=make(chan string)
msg := "h1"
go func(msg string) {
select {
case messages <- msg:
fmt.Println("sent message", msg)
}
}(msg)
select {
case msg := <-messages:
fmt.Println("Message recieved", msg)
}
}