我在 Go 中有一个返回两个值的函数。我想将其作为 goroutine 运行,但我无法弄清楚创建接收两个值的通道的语法。有人能指出我正确的方向吗?
			
			38323 次
		
2 回答
            55        
        
		
定义一个包含两个值的字段的自定义类型,然后创建chan该类型的一个。
编辑:我还添加了一个使用多个通道而不是自定义类型的示例(在底部)。我不确定哪个更惯用。
例如:
type Result struct {
    Field1 string
    Field2 int
}
然后
ch := make(chan Result)
使用自定义类型(Playground)通道的示例:
package main
import (
    "fmt"
    "strings"
)
type Result struct {
    allCaps string
    length  int
}
func capsAndLen(words []string, c chan Result) {
    defer close(c)
    for _, word := range words {
        res := new(Result)
        res.allCaps = strings.ToUpper(word)
        res.length = len(word)
        c <- *res       
    }
}
func main() {
    words := []string{"lorem", "ipsum", "dolor", "sit", "amet"}
    c := make(chan Result)
    go capsAndLen(words, c)
    for res := range c {
        fmt.Println(res.allCaps, ",", res.length)
    }
}
产生:
LOREM , 5
IPSUM , 5
DOLOR , 5
SIT , 3
AMET , 4
编辑:使用多个通道而不是自定义类型来产生相同输出的示例(Playground):
package main
import (
    "fmt"
    "strings"
)
func capsAndLen(words []string, cs chan string, ci chan int) {
    defer close(cs)
    defer close(ci)
    for _, word := range words {
        cs <- strings.ToUpper(word)
        ci <- len(word)
    }
}
func main() {
    words := []string{"lorem", "ipsum", "dolor", "sit", "amet"}
    cs := make(chan string)
    ci := make(chan int)
    go capsAndLen(words, cs, ci)
    for allCaps := range cs {
        length := <-ci
        fmt.Println(allCaps, ",", length)
    }
}
    于 2013-07-24T05:35:19.663   回答
    
    
            17        
        
		
另一种选择是使用 anon 函数,如下所示:
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)
}
归功于https://gist.github.com/slav/ca2ee333c29b8f76b557c9b10b371b52
于 2018-06-14T12:10:26.867   回答