内容简介:之前在做其他语言是,对于异步调用,总有返回值和错误返回,并且能接收,对其进行处理。在go语言中,对于协程goroutine的返回值(包括错误)怎么捕获呢?
之前在做其他语言是,对于异步调用,总有返回值和错误返回,并且能接收,对其进行处理。
在 go 语言中,对于协程 goroutine 的代码,因为没有返回值接收,导致新手在学习时候会有困惑:
goroutine的返回值(包括错误)怎么捕获呢?
下面我们写一个列子来说明下。
package main
import (
"fmt"
"log"
"time"
)
type Resp struct {
data int
error error
}
func main() {
handleMsg()
}
func handleMsg() {
resp := make(chan Resp)
stop := make(chan struct{})
go func() {
t := time.Tick(time.Second)
index := 0
for {
select {
case <-t:
resp <- Resp{
data: index,
}
index++
case <-stop:
resp <- Resp{
error: fmt.Errorf("time tick stop error"),
}
}
}
}()
for {
select {
case val := <-resp:
if val.error != nil {
log.Fatal(val.error)
}
if val.data == 5 {
stop <- struct{}{}
}
fmt.Println("index", val.data)
}
}
}
这里 Resp 封装了接收值和错误类型,
type Resp struct {
data int
error error
}
利用select的接手值,来判断当前goroutine的结果是否正确。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- js捕获错误信息
- Python捕获所有异常
- Android NativeCrash 捕获与解析
- Wireshark如何捕获USB流量
- 在 Docker 容器中捕获信号
- Laravel异常:捕获,处理和创建
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Unreal Engine 4 Scripting with C++ Cookbook
Sherif, William、Stephen Whittle / 2016-10-24
Unreal Engine 4 (UE4) is a complete suite of game development tools made by game developers, for game developers. With more than 100 practical recipes, this book is a guide showcasing techniques to us......一起来看看 《Unreal Engine 4 Scripting with C++ Cookbook》 这本书的介绍吧!