The following code works okay
func main() {
c := make(chan string)
go subRountine(c)
fmt.Println(<-c)
}
func subRountine(c chan string) {
c <- "hello"
}
Is there any other method to create a channel without the make function? Something like this but this sample does not work
func main() {
var c chan string
go subRountine(c)
fmt.Println(<-c)
}
func subRountine(c chan string) {
c <- "hello"
}
CodePudding user response:
TL;DR
No way around it: you must use make
.
More details
var c chan string
merely declares a channel variable, but without initialising the channel! This is problematic because, as the language spec puts it
The value of an uninitialized channel is
nil
.
and
A
nil
channel is never ready for communication.
In other words, sending and/or receiving to a nil
channel is blocking. Although nil
channel values can be useful, you must initialise a channel at some stage if you ever want to perform channel communications (send or receive) on it.
As mkopriva writes in his comment, Go provides only one way of initialising a channel:
A new, initialized channel value can be made using the built-in function
make
, which takes the channel type and an optional capacity as arguments:make(chan int, 100)
CodePudding user response:
No! Declaring a channel with var
is different from creating it. Then you should create by make
:
var c chan string
c = make(chan string)
With the difference that now you can make c in underlying scops and use it outside of them.
Note that you shouldn't put colons before the equals sign in this way.