2013-07-24 5 views

答えて

29

両方の値のフィールドを持つカスタムタイプを定義し、そのタイプのchanを作成します。

EDIT:カスタムタイプではなく複数のチャンネルを使用する例(右下)も追加しました。私はどちらがもっと熟語的かわからない。カスタムタイプのチャネル(Playground)を使用しての

type Result struct { 
    Field1 string 
    Field2 int 
} 

次いで

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
イプサム、5
悲しみ、5
SIT、3
AMET、4

EDIT:同じ出力を生成する代わりに、カスタム・タイプの複数のチャネルを使用して、実施例(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)'やそれに類するものを行い、関連するデータ構造を "舞台裏で"作ることができるのはクールです。おそらくGo機能の要望に値するでしょうか? – Intermernet

関連する問題