vlang: error: Option function field must be unwrapped first

139 views Asked by At

I'm using the PICOEV lib and got this error: Option function field must be unwrapped first

unsafe { target.cb(event.data.fd, read_events, &pv) }
// target is defines as:
pub struct Target {
pub mut:
    fd      int
    loop_id int = -1
    events  u32
    cb      fn (int, int, voidptr) or { none}
    backend int
}

I can't get my head around how to implement an 'or { nill }' for unwrapping

Any help appreciated

Got to the problem by: try to compile my own code and/ then got same error with the official PICO demo example.

2

There are 2 answers

0
impopularGuy On

EDIT: I just checked, it has been updated. https://github.com/vlang/v/blob/7ca23f6316ea4ee9e70ad8acb95ba5f11e34434f/vlib/picoev/picoev.v#L26C49-L26C49

If you are trying to give a default value to a function-type field the use unsafe { nil }. So the struct definition would be

pub struct Target {
pub mut:
    fd      int
    loop_id int = -1
    events  u32
    cb      fn (int, int, voidptr) = unsafe { nil }
    backend int
}

When using cb field, we need to check if it is not nil

if target.cb != unsafe { nil } {
    target.cb(event.data.fd, read_events, &pv)
}
0
BrotherAdam On

What you’re looking for is the Option type. The use of unsafe { nil } is typically discouraged now that Option type is available as struct fields. You can view the Options/Results section of the docs for more info. Notice the ? before the type of the cb field:

pub struct Target {
pub mut:
    fd      int
    loop_id int = -1
    events  u32
    // this field is assigned the `none` keyword by default
    cb      ?fn (int, int, voidptr)
    backend int
}

Then to access the Option field try this:

if cb := target.cb {
    cb(event.data.fd, read_events, &pv)
}