Hi,
please consider the following code:
const std = @import("std");
const myenum = enum { a, b };
pub fn foo1(mye: myenum) void {
const val = 1 + switch (mye) {
.a => 1,
.b => 2,
};
std.debug.print("{d}\n", .{val});
}
fn foo2(mye: myenum) void {
const val: u8 = 1 + switch (mye) {
.a => 1,
.b => 2,
};
std.debug.print("{d}\n", .{val});
}
fn foo3(mye: myenum) void {
const val: u8 = 1 + @as(u8, switch (mye) {
.a => 1,
.b => 2,
});
std.debug.print("{d}\n", .{val});
}
fn foo4(mye: myenum) void {
var val: u8 = 1;
val += switch (mye) {
.a => 1,
.b => 2,
};
std.debug.print("{d}\n", .{val});
}
pub fn main() !void {
foo1(.a);
}
When main calls foo1, I get a compile error:
main.zig:5:21: error: value with comptime-only type 'comptime_int' depends on runtime control flow
const val = 1 + switch (mye) {
^~~~~~
main.zig:5:29: note: runtime control flow here
const val = 1 + switch (mye) {
^~~
Ok, that makes sense. 1 is a comptime literal, and the switch depends on the function argument. I guess I add a type annotation. So I call foo2, where I specified the type of the result.
But I still get
main.zig:13:25: error: value with comptime-only type 'comptime_int' depends on runtime control flow
const val: u8 = 1 + switch (mye) {
^~~~~~
main.zig:13:33: note: runtime control flow here
const val: u8 = 1 + switch (mye) {
^~~
Wow, do I really have to specify that the switch should produce a u8? Yes I do, as I did in foo3. This compiles and runs. But alternatively, I could have made the result a var and do the operations in individual steps like I did in foo4. Here I do not need a type annotation for the switch (why?), but I loose the information that val will not change anymore throughout the function.
I wondered why I have to do extra work here in order to compile.
Is this explicit type casting required in a similar setting, where the types are not that obvious?
Is the type inference system work in progress and this will be possible at some point?
It is ok, if I have to do the extra annotations, I just want to know why they are necessary like in foo3, but not in foo4.
Thank you for your answers,