Is it possible to let function funcWithNonChanResult
have the following interface:
func funcWithNonChanResult() int {
And if I want it to use function funcWithChanResult
with the interface:
func funcWithChanResult() chan int {
In other words, can I somehow convert chan int
to int
? Or I must have chan int
result type in all the functions which use funcWithChanResult
?
Currently, I tried these methods:
result = funcWithChanResult()
// cannot use funcWithChanResult() (type chan int) as type int in assignment
result <- funcWithChanResult()
// invalid operation: result <- funcWithChanResult() (send to non-chan type int)
Full code:
package main
import (
"fmt"
"time"
)
func getIntSlowly() int {
time.Sleep(time.Millisecond * 500)
return 123
}
func funcWithChanResult() chan int {
chanint := make(chan int)
go func() {
chanint <- getIntSlowly()
}()
return chanint
}
func funcWithNonChanResult() int {
var result int
result = funcWithChanResult()
// result <- funcWithChanResult()
return result
}
func main() {
fmt.Println("Received first int:", <-funcWithChanResult())
fmt.Println("Received second int:", funcWithNonChanResult())
}
A
chan int
is a channel ofint
values, it is not a singleint
value but a source ofint
values (or also a target, but in your case you use it as source).So therefore you can't convert
chan int
toint
. What you can do and probably what you mean is use a value (of typeint
) received from achan int
as anint
value.This is not a problem:
Or more compact:
Combine this with the
return
statement:Output (as expected):
Try your modified, working example on the Go Playground.