Code styles
All of the above affirmations are taken from the Zig Style Guide itself.
Here we just point out what we consider the most important.
Style guide
fmt
First it is important to know that Zig comes with a formatter that you can use using:
zig fmt file.zig
This util is going to enforce basic things for you like:
- Indentation
- Braces alignment
- Line length
Naming conventions
TitleCaseTypeName
: for types and structs that are callable (for "classes" in other languages basically)camelCaseFunctionName
: for functionssnake_case_variable_name
: for variables and everything else
To get more details you can read the official documentation about this topic.
Not that those conventions are not going to be enforced by the formatter.
undefined and null values
In Zig you can leave variables uninitialized, but you have to do that explicitly contrary to C where you can leave variables uninitialized and never truly notice it. Note that leaving the value undefined is going to leave the memory of this variable to some complete unpredicatble value (except in Debug mode where it will be set to 0xaa)
const stdout = std.io.getStdOut();
const my_var: u8 = undefined;
try stdout.writer().print("my_var: {}\n", .{my_var});
my_var: 0
This is to be avoided as much as possible, if you have some in your code it might makes sense to use an Optional type instead so that compiler can scream at you :)
const stdout = std.io.getStdOut();
const my_var: ?u8 = null;
// .? is syntaxic sugar for "orelse unreachable" which is going
// unreachable is going to emit a panic (unable to unwrapp null) !
// THIS CODE WILL PANIC IF UNCOMMENTED
// _ = my_var.?;
// if value is "null" then "42" will be assigned
const value: u8 = my_var orelse 42;
// print 42 because value was null before
try stdout.writer().print("my_var: {}\n", .{value});
Zen
Zig encourages you to use the Zen philosophy, they reflect well the spirit behind Zig. Having them in mind while coding in Zig can be very beneficial to help you understand how Zig works and help you write better code.
Here are those principales taken exactly as they are in the documentation:
- Communicate intent precisely.
- Edge cases matter.
- Favor reading code over writing code.
- Only one obvious way to do things.
- Runtime crashes are better than bugs.
- Compile errors are better than runtime crashes.
- Incremental improvements.
- Avoid local maximums.
- Reduce the amount one must remember.
- Focus on code rather than style.
- Resource allocation may fail; resource deallocation must succeed.
- Memory is a resource.
- Together we serve the users.