2013-07-24 30 views

回答

29

用两个值的字段定义自定义类型,然后创建该类型的chan

编辑:我也添加了一个例子(在底部),使用多个渠道,而不是自定义类型。我不确定哪一种比较习惯。

例如:

type Result struct { 
    Field1 string 
    Field2 int 
} 

然后使用自定义类型的沟道(Playground)的

ch := make(chan Result) 

实施例:

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) 
    } 
} 
+1

@ nick-craig-wood感谢您的编辑,我的部分草率提交。 – Intermernet

+2

这太糟糕了;它似乎击败了允许多个返回值的全部点 –

+4

有趣的一点。能够执行'c:= make(chan string,err)'或类似的命令并且在“幕后”创建相关的数据结构将会很酷。也许值得一个去功能请求? – Intermernet

相关问题