How to make a channel that receive multiple return values from a goroutine

后端 未结 2 710
别跟我提以往
别跟我提以往 2021-02-01 12:31

I have a function in Go that returns two values. I want to run this as a goroutine, but I can\'t figure out the syntax for creating a channel that receives two values. Could som

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 13:25

    Another option would be to use an anon function like so:

    package main
    
    import "fmt"
    
    func f(c chan func() (int, string)) {
        c <- (func() (int, string) { return 0, "s" })
    }
    
    func main() {
        c := make(chan func() (int, string))
        go f(c)
        y, z := (<-c)()
        fmt.Println(y)
        fmt.Println(z)
    }
    

    Credit to https://gist.github.com/slav/ca2ee333c29b8f76b557c9b10b371b52

提交回复
热议问题