简体   繁体   中英

How to compare errno in Go?

In Cgo, you can't get the value of errno directly, but you can get the result of it after a function call using a double return value. eg ret, err := C.write(...) . However, it seems like this err is just an opaque error interface and can't be compared with errno constants. How can I do, eg something like this:

ret, err := C.my_func()
if ret == -1 {
    // error signaled
    if err == C.EAGAIN {
        // do it again
    } else {
        return err
    }
} else {
    ...
}

This code does not compile since invalid operation: err == _Ciconst_EAGAIN (mismatched types error and int) . Is this even possible?

The error type will be syscall.Errno , which you can assert and compare.

ret, err := C.my_func()
if errno, ok := err.(syscall.Errno); ret == -1 && ok {
    // error signaled
    if errno == C.EAGAIN {
        // do it again
    } else {
        return err
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM