I have a function, which first validates a clipping.
If OK it performs its inner logic.
Now I would like to discard the ‘perform_clipping’ result. WIthout ‘catch’ if possible.
pub fn copy_rect(...) !void // todo: no result
{
const clip: coords.ValidClip = try coords.perform_clipping(...);
internal_copy_rect(clip);
}
Is something like this possible?
It seems so, but can’t generate the right syntax
pub fn copy_rect(...) void // no result
{
if (perform_clipping(...)) |clip|
{
internal_copy_rect(clip);
}
}
I don’t know if this is applicable, but if you want to “discard” an error, you can always say it’s unreachable or put a default
so
pub fn copy_rect(...) void
{
const clip: coords.ValidClip = coords.perform_clipping(...) catch unreachable;
internal_copy_rect(clip);
}
or
pub fn copy_rect(...) void
{
const clip: coords.ValidClip = coords.perform_clipping(...) catch <your default value>;
internal_copy_rect(clip);
}
or I think you can do something like that too
pub fn copy_rect(...) void
{
if (perform_clipping(...)) |clip|
{
internal_copy_rect(clip);
}else |_| {
}
}
1 Like
Would catch return
work for you?
Yes that would work.
The only thing is that this ‘catch’ sounds like something terrible happened.
I guess that comes from my C# background…
This ‘catch’ can we read as ‘discard returned error enum’? (and return void)
edit: the only error returned is: ClippingError.Empty
I read catch return
as "on error, exit from this function. If you aren’t expecting this error to ever be returned, you can use catch unreachable
or catch @panic("didn't expect this to happen")
.
If the function you’re calling is void, you can also use catch {}
, which means “on error, ignore it and continue”. In this case you have a non-void
return value to deal with though.
Yes, normally we return !void
.
And we use try
to early exit with the error.
But in this (rendering) case I don’t need the result at all, that’s why.
Thanks!
Coming back to this: I discovered we can use a ?void.
fn check(x: i32) ?void
{
if (x > 1600) return null;
}
fn do_something() void
{
check(42) orelse return;
}
Because - in my case - I am totally not interested in any return value.
I cannot verify if it is better or faster or crazy.
But the orelse
looks more friendly than catch