栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使通道从goroutine接收多个返回值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使通道从goroutine接收多个返回值

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

chan
该类型的。

编辑:我还添加了一个使用多个通道而不是自定义类型的示例(在底部)。我不确定哪个更惯用。

例如:

type Result struct {    Field1 string    Field2 int}

然后

ch := make(chan Result)

使用自定义类型的频道(Playground)的示例:

package mainimport (    "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
颜色,5
SIT,3
AMET,4


编辑:使用多个通道而不是自定义类型来产生相同输出(Playground)的示例:

package mainimport (    "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)    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/435156.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号