#inline question
1 messages · Page 1 of 1 (latest)
this code works, because of inlining:
pub fn main() !void {
const num: comptime_int = foo();
std.debug.print("{}\n", .{num});
}
inline fn foo() comptime_int {
std.debug.print(
\\I am a runtime operation,
\\even though the function returns a comptime value!
\\
, .{});
return 42;
}
think about how might the foo example be inlined
something like that
obviously things can get more complex (think: function arguments), but replacement with a block is a reasonable mental model
replacement with a block is very close to what happens in the compiler in fact
the only thing that can't be directly translated to a block is inferred error sets
ignoring variable name conflicts, you can think of it as doing this:
inline fn foo(a: u32, b: u32) !u16 {
const c = try something_else();
if (c == 0) return 123;
return @intCast(a - b);
}
fn outer() {
const result = try foo(1, 2);
do_something(result);
}
// becomes
fn outer() {
const result: = try @as((somehow inferred)!u16, blk: {
const a: u32 = 1;
const b: u32 = 2;
const c = something_else() catch |err| break :blk err;
if (c == 0) break :blk 123;
break :blk @intCast(a - b);
});
do_something(result);
}
(somehow inferred) is a little magic, because of course you can't write const result: !u16 = ...