Hello,
I am trying to see how one deals with a value of !? type. Tried to find an example with no success. Initially I started with this very basic example:
const a: ?f32 = null;
const fallback_value: f32 = 0;
const b = a orelse fallback_value;
try expect(b == 0);
try expect(@TypeOf(b) == f32);
Works as expected. Later I tried the following:
pub const Save = struct {
lives: u8,
level: u16,
pub fn loadLast() !?Save {
//todo
// return null;
// return .{
// .lives = 30,
// .level = 100,
// };
return C.NotDir;
}
pub fn blank() Save {
return .{
.lives = 3,
.level = 1,
};
}
};
const OpenError = error{
AccessDenied,
NotFound,
};
const A = error{ NotDir, PathNotFound };
const B = error{ OutOfMemory, PathNotFound };
const C = A || B;
pub fn main() !u8 {
...
{
const save: Save = try Save.loadLast() orelse Save.blank();
std.debug.print("{any}\n", .{save});
}
...
}
I expected the output of blank()
but get error: NotDir
printed to console. Using:
const save: Save = (try Save.loadLast() orelse Save.blank());
and
const save: Save = (try Save.loadLast()) orelse Save.blank());
produces the same results. I also tried to reduce this to a minimal example with:
const a1: !?f32 = null;
const fallback_value1: f32 = 0.1;
const b1 = a1 orelse fallback_value1;
try expect(b1 == 0.1);
try expect(@TypeOf(b) == f32);
but compilation fails with:
src/example_5.zig:186:15: error: expected type expression, found '!'
const a1: !?f32 = null;
So I have 2 questions. First, what is the idiomatic way of dealing with !?
types? Second, how can one declare a type !?f32
to make the last experiment work?
TIA