cry0genic
cry0genic

Reputation: 593

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. e.g. 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, e.g. 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?

Upvotes: 1

Views: 1967

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109425

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
    }
}

Upvotes: 3

Related Questions