Golang - 这个函数是如何被调用的

标签 go

我正在使用 this sample代码,但无法理解如何调用此函数以及属于哪个参数。

go func(r []string) {
    processData(r)
    ch <- r
}(record)

最佳答案

function closures :

Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.

要理解这一点:

go func(r []string) {
    processData(r)
    ch <- r
}(record)

让我们先声明这个函数:

func routine(r []string) {
    processData(r)
    ch <- r
}

和这个全局变量:

var ch = make(chan []string)

现在你可以称它为:

go routine(record)

这调用名为 routine 的函数,输入参数名为 record 作为 goroutine。

并查看:https://gobyexample.com/goroutines

试试The Go Playground :

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "io"
    "os"
    "strings"
    "time"
)

func routine(r []string) {
    processData(r)
    ch <- r
}

var ch = make(chan []string)

func main() {
    start := time.Now()
    flag.Parse()
    fmt.Print(strings.Join(flag.Args(), "\n"))
    if *filename == "REQUIRED" {
        return
    }

    csvfile, err := os.Open(*filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer csvfile.Close()

    reader := csv.NewReader(csvfile)

    i := 0
    for {
        record, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            fmt.Println(err)
            return
        }
        i++

        go routine(record)

        fmt.Printf("go %d %s\n", i, record)
    }
    for ; i >= 0; i-- {
        fmt.Printf("<- %d %s\n", i, <-ch)
    }

    fmt.Printf("\n%2fs", time.Since(start).Seconds())

}

func processData([]string) {
    time.Sleep(10 * time.Millisecond)
}

var filename = flag.String("f", "REQUIRED", "source CSV file")
var numChannels = flag.Int("c", 4, "num of parallel channels")

//var bufferedChannels = flag.Bool("b", false, "enable buffered channels")

关于Golang - 这个函数是如何被调用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815778/

相关文章:

go - 为什么在 Error() 方法中调用 fmt.Sprint(e) 会导致无限循环?

angularjs - 你如何设置 go 服务器以与 AngularJS html5mode 兼容?

go - Go中的链接函数?

mysql - 批量 MySQL 插入比 PHP 慢 2 倍

go - 痛饮 + 去 : unsupported relocation for dynamic symbol

linux - 在 golang 中写在热敏打印机设备上

go - 如何保证Golang channel 等待数据,Stdin没有数据时程序不终止

debugging - 进入程序运行时错误并打印出所有内容

go - 如何将 SQLite 数据库捆绑到 Go 二进制文件中?

regex - 如何使用 golang 正则表达式引用组