面试题答案
一键面试package main
import (
"fmt"
)
// 定义结果结构体
type Result struct {
success bool
data interface{}
}
func main() {
// 模拟多个goroutine的结果
results := []Result{
{success: true, data: "data1"},
{success: true, data: "data2"},
{success: true, data: "data3"},
}
allSuccess := true
var mergedData []interface{}
for _, result := range results {
if!result.success {
allSuccess = false
break
}
mergedData = append(mergedData, result.data)
}
if allSuccess {
fmt.Println(mergedData)
} else {
fmt.Println("有goroutine处理失败")
}
}
上述代码实现了对多个goroutine
返回结果的判断与合并。在实际场景中,results
切片的数据应是从不同goroutine
实际返回获取。这里只是模拟数据。如果要从真实的goroutine
获取数据,可以使用channel
来接收每个goroutine
返回的结果,如下示例:
package main
import (
"fmt"
)
// 定义结果结构体
type Result struct {
success bool
data interface{}
}
func worker(id int, resultChan chan<- Result) {
// 模拟业务处理
if id%2 == 0 {
resultChan <- Result{success: true, data: fmt.Sprintf("worker %d data", id)}
} else {
resultChan <- Result{success: false, data: nil}
}
close(resultChan)
}
func main() {
numWorkers := 3
var allSuccess = true
var mergedData []interface{}
for i := 0; i < numWorkers; i++ {
resultChan := make(chan Result)
go worker(i, resultChan)
for result := range resultChan {
if!result.success {
allSuccess = false
} else {
mergedData = append(mergedData, result.data)
}
}
}
if allSuccess {
fmt.Println(mergedData)
} else {
fmt.Println("有goroutine处理失败")
}
}
在这个改进版本中,worker
函数模拟一个goroutine
的工作,通过channel
返回结果。main
函数启动多个worker
,并从channel
接收结果,进行判断和合并操作。这样更符合实际的并发处理场景。