Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/functions.zig

65 lines
1.6 KiB

const std = @import("std");
const debug = std.debug;
const testing = std.testing;
fn add(a: i8, b: i8) i8 {
if (a == 0) {
return b;
}
return a + b;
}
// export ensures that the exported function conforms to the C ABI.
export fn sub(a: i8, b: i8) i8 {
return a - b;
}
// extern is the same as in C - resolve the symbol at linktime (static) or runtime (dynamic)
extern "c" fn atan2(a: f64, b: f64) f64;
extern "c" fn printf(fmt: [*:0]const u8, ...) c_int;
test "extern" {
debug.print("atan2({}, {}) = {}\n", .{ 1.2, 2.3, atan2(1.2, 2.3) });
_ = printf("Hello, %s\n", "world");
}
// force inline, and if not possible, throw a comptime error.
fn shitfLeftByOne(a: u32) callconv(.Inline) u32 {
return a << 1;
}
// pub make the function visible to other modules
pub fn foo() void {}
// callbacks
const call2_op = fn (i8, i8) i8;
fn doWork(f: call2_op, x: i8, y: i8) i8 {
return f(x, y);
}
test "callbacks" {
testing.expectEqual(doWork(add, 1, 41), 42);
}
// the @setCold builtin marks a functon a being rarely used
fn abort() noreturn {
@setCold(true);
while (true) {} // this is why the return type is noreturn
}
// Naked marks a function as having no prologue and epilogue - useful when working with assembly
fn _start() callconv(.Naked) noreturn {
abort();
}
fn bar() void {}
test "function values are like pointers" {
comptime {
testing.expectEqual(@TypeOf(bar), fn () void);
testing.expectEqual(@sizeOf(fn () void), @sizeOf(?fn () void));
testing.expectEqual(@sizeOf(*i32), @sizeOf(?*i32));
}
}