package main
import "fmt"
var money int = 100
var update = make(chan int)
func updateM( count int) {
update<- count
}
func main() {
updateM(200)
fmt.Println(<-update)
}
but when i change the code to add a go in front of updateM(200) then no error
func main() {
go updateM(200)
fmt.Println(<-update)
}
could anyone tell me , i am new learner of Go. Thanks a lot.
A write to an unbuffered channel will block until there's someone reading it at the other end. In your case updateM
will block indefinitely because to continue, it needs to continue so that it can read from the channel, which it can't because it's not reading from the channel.
Channels are for communication between goroutines, they don't make sense for talking to yourself.
From the documentation:
If the channel is unbuffered, the sender blocks until the receiver has received the value. If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.
You can make it not blocking by changing the channel creation to
var update = make(chan int, 1)
so that there's room for one item in the channel before it blocks.