我正在使用 this sample代码,但无法理解如何调用此函数以及属于哪个参数。
go func(r []string) {
processData(r)
ch <- r
}(record)
最佳答案
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
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/