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 someone point me in the right direction?
2条回答 默认 最新
- doubu1950 2013-07-24 05:35关注
Define a custom type with fields for both values, then create a
chan
of that type.EDIT: I've also added an example (right at the bottom) that uses multiple channels rather than a custom type. I'm not sure which is more idiomatic.
For example:
type Result struct { Field1 string Field2 int }
then
ch := make(chan Result)
Example of using a channel of a custom type (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) } }
Produces:
LOREM , 5
IPSUM , 5
DOLOR , 5
SIT , 3
AMET , 4EDIT: Example using multiple channels instead of a custom type to produce the same output (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) } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
- ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
- ¥15 win10,这种情况怎么办
- ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
- ¥100 在连接内网VPN时,如何同时保持互联网连接
- ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
- ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
- ¥50 win10 LTSC 虚拟键盘不弹出
- ¥30 微信小程序请求失败,网页能正常带锁访问
- ¥15 Matlab求解微分方程,如何用fish2d进行预优?