#what's the meaning and use case of void and !void

1 messages · Page 1 of 1 (latest)

light marlin
#

Example

fn name() void {}
fn name() !void {}```
tidal tapir
#

void means it returns nothing

#

!void means it returns either nothing, or an error from an inferred error union (zig looks at which errors your function can actually return)

light marlin
#

So more like the any for zig?

tidal tapir
#

for instance, allocators return error.OutOfMemory when they fail, so if your function calls try allocator.alloc(whatever), zig notices that it could return that error so its return type is essentially error{OutOfMemory}!void

tidal tapir
#

there is also an anyerror keyword which is different... idk when you need that in practice

#

maybe for function pointers?

#

anyerror means "can return any error". omitting the error union means "can return any error from a finite set, but i don't want to write out that finite set"

light marlin
#

Ok thanks i understand it now

tidal tapir
#

:D

light marlin
#

Is it a must i put it when a fn is not returning something ?

tidal tapir
#

you can't omit the return type, you need to write void explicitly

light marlin
#

Because it look like a type definition

tidal tapir
#

void means "returns nothing"
!void means "returns nothing or an error"

#

same for other types btw, you can have for instance !u32 for "error or a u32"

light marlin
tidal tapir
#

fn name() void {}

light marlin
#

But it's more like inferring the type?

tidal tapir
#

void doesn't do any inference
!void means the set of errors that can be returned by your function is inferred

#

only the errors returned by a function can be inferred, the return type itself has to be written explicitly

light marlin
#

Ok thanks