登录
首页 >  Golang >  Go问答

从 goroutine 中接收多个返回值

来源:stackoverflow

时间:2024-02-21 12:12:21 192浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《从 goroutine 中接收多个返回值》,涉及到,有需要的可以收藏一下

问题内容

我正在尝试用 Go 编写 wc(1),并且正在尝试使用 goroutine 来更有效地计算大量输入文件。我的代码工作正常,但我很难实现一种方法来总结所有 go 例程的统计信息。如何将函数变量 nlnwnc 传递给 main,并在所有 go 例程完成工作后在那里汇总它们?

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    ch := make(chan string)

    for _, arg := range os.Args[1:] {
        go wc(arg, ch)
    }
    for range os.Args[1:] {
        fmt.Println(<-ch)
    }
    // Todo: summarize results...
}

func wc(arg string, ch chan<- string) {
    nl, nw, nc := 0, 0, 0

    file, err := os.Open(arg)
    if err != nil {
        fmt.Println("Can't open file: %v", err)
    }
    defer file.Close()

    scan := bufio.NewScanner(file)
    for scan.Scan() {
        nl++

        line := scan.Text()
        words := bufio.NewScanner(strings.NewReader(line))
        words.Split(bufio.ScanWords)
        for words.Scan() {
            nw++
        }

        runes := bufio.NewReader(strings.NewReader(line))
        for {
            if _, _, err := runes.ReadRune(); err != nil {
                break
            } else {
                nc++
            }
        }
    }

    ch <- fmt.Sprintf("%8d%8d%8d", nl, nw, nc+nl)
}

正确答案


您已经接近答案了!我建议快速重构,返回带有数字的 Result 对象,这将允许轻松地在末尾添加它们(而不是使用字符串)。因此,您可以使用 chan 结果 而不是 chan string

基本上,您可以引入一个 totalResult 变量,并且在迭代所有结果时,只需将 nlncnw 的结果添加到该总变量中。

package main

import (
    "fmt"
    "math/rand"
)

// define a struct to hold the result
type Result struct {
    nl int
    nw int
    nc int
}

// this is to be able to use fmt.Println(result)
func (r Result) String() string {
    return fmt.Sprintf("%8d%8d%8d", r.nl, r.nw, r.nc+r.nl)
}

func main() {
    ch := make(chan Result)

    for _, arg := range os.Args[1:] {
        go wc(arg, ch)
    }

    totalResult := Result{}

    for range os.Args[1:] {
        result := <-ch
        fmt.Println(result) // just for debugging

        // sum everything
        totalResult.nl += result.nl
        totalResult.nw += result.nw
        totalResult.nc += result.nc
    }

    fmt.Println("Total result:")
    fmt.Println(totalResult)
}

func wc(arg string, ch chan<- Result) {
    nl, nw, nc := 0, 0, 0

    // your logic to compute nl, nw, nc goes here

    ch <- Result{nl: nl, nw: nw, nc: nc + nl}
}

您应该得到类似这样的内容(包含 3 个文件):

37      50    4753
      19     106     821
      47     255    3806
Total result:
     103     411    9380

到这里,我们也就讲完了《从 goroutine 中接收多个返回值》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>