Skip to content

Instantly share code, notes, and snippets.

@qgcarver
Created October 25, 2020 04:21
Show Gist options
  • Save qgcarver/2f6a54506e4f8b2d22bcbdef55b609e1 to your computer and use it in GitHub Desktop.
Save qgcarver/2f6a54506e4f8b2d22bcbdef55b609e1 to your computer and use it in GitHub Desktop.
comptime ignored?
const std = @import("std");
const names_and_vals = [_]struct{name: []const u8, value: u32}{
.{.name = "first" , .value = 0x1},
.{.name = "second" , .value = 0x2},
.{.name = "third" , .value = 0x3},
};
fn name_to_val(comptime name: []const u8) u32 {
comptime {
var return_val: u32 = undefined;
for(names_and_vals) |tuple, idx| {
if(std.mem.eql(u8, tuple.name, name)) {
return_val = tuple.value;
return return_val;
}
} else unreachable;
}
}
pub fn main() void {
const val = 0x3;
std.debug.print("\n -> ", .{});
switch (val) {
name_to_val("first") => {
std.debug.print("first\n", .{});
return;
},
name_to_val("second") => {
std.debug.print("second\n", .{});
return;
},
name_to_val("third") => std.debug.print("third\n", .{}),
else => {
std.debug.print("last\n", .{});
return;
}
}
_ = name_to_val("invalid"); //invalid, but only hits 'unreachable' at runtime
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment