Leenuus/ziglings-solutions
Clone from Ziglings
defer
and errdefer
keyword makes life easierenum
, btw, Zig's enum
is much more understandable and writable than the Rust oneswitch
statementunreachable
keyword optimization hints to the compiler, also as placeholder for programmerResult
with Option
inside adding generic annotation.mut
in front of it.comptime
code generation is a better idea.This is important to figure out how assignment works when learning a new programming language.
In Zig, assignment works this way:
mut var: type
, mut var: &type
, mut var: &mut type
, var: &type
, var: &mut type
, var: type
to specify the incoming parameter. The mut
comes in front of the variable name var
indicates whether var
is rebindable. And the following annotions indicate the type of the parameter. &mut type
means mutable reference; you use this type to modify the value outside of the function, invoking side effects. &type
means immutable reference; you can only read the variable, not allowed to change it. type
is a way to consume the value passed in, which indicates you don't need this value anymore after executing the function, so Rust compiler could safely release the memory it takes.var a = struct A{}; var b = [a, a];
works differently in different languages too. But in fact, it is just assignment. So for languages like C, Zig and Cpp, the array b
just gets two copy of a
, consuming it own space.Are all of these pointer types starting to get confusing?
FREE ZIG POINTER CHEATSHEET! (Using u8 as the example type.)
+---------------+----------------------------------------------+
| u8 | one u8 |
| *u8 | pointer to one u8 |
| [2]u8 | two u8s |
| [*]u8 | pointer to unknown number of u8s |
| [*]const u8 | pointer to unknown number of immutable u8s |
| *[2]u8 | pointer to an array of 2 u8s |
| *const [2]u8 | pointer to an immutable array of 2 u8s |
| []u8 | slice of u8s |
| []const u8 | slice of immutable u8s |
+---------------+----------------------------------------------+
Enum with wrapped value is somehow union in fact.
enum Fruit{
Apple(Apple),
Grape(Grape),
}
struct Apple;
struct Grape;
I mean, union is a way to save memory in machine level, but in a programmer perspctive, it gives a way to express these things are things in the same group. And what about enum? It is a way to express that there are A, B, C, D, total 4 options in this circumstances. So when you combine two concepts, you get a way to indicate a group, also a way to specify the certain thing belonged to this group. To be short, union creates a namespace holding the options, and enum indicates one option, a fancy name, variant, in this namespace.
So in Zig, there is something like
const Insect = union(enum) {
flowers_visited: u16,
still_alive: bool,
};
// The same as the following
const InsectStat = enum { flowers_visited, still_alive };
const Insect = union(InsectStat) {
flowers_visited: u16,
still_alive: bool,
};