279 points · by dnautics · 5y ago · 158 comments
If I may here are three additional pieces of information that if added to your documentation will clarify some more things for the beginner/reader:
1) Arrays and Slices section
Arrays in Zig are values. They store the pointer and the length, but an array is a value so the raw pointer can never be accesses unless....
You coerce the array to a slice. A slice reveals a pointer to you.
2) Add tagged unions (I do not understand what they are but they exist, maybe some fellow reader here could help me)
3) If, for, while and switch can ALSO BE EXPRESSIONS!
Now to the part that does not address you directly but everyone.
These tutorials are great, but they are the mere starting point. I admire Zig and its design, I admire Andrew and that awesome community, I love Zig Showtime and everything. But there are two problems I have with Zig that annoy me and that is only because I REALLY want to learn it and ditch C already:
* I am trying to figure out how to do system's programming. Like use all the system calls and their system library wrapper equivalent's that I am so used to in C. After an hour of research on the net I could not even figure out how to read in and go through the contents of a file (fread, fstat, fgets, fopen). That stuff needs to go into the official documentation or at least to ziglearn.org
* The same way the Zig compiler is awesome the underlying build file you often wanna write is just horribly documented. I don't understand half of it and it changes a lot. Andrew should really politely ask people on the internet to take down old repos and blog entries. Please document the build system and build file writing better.
https://ziglearn.org/chapter-2/#filesystem
And details on reading the next line here:
https://ziglearn.org/chapter-2/#readers-and-writers
fread/fstat/fgets/fopen is now all covered. The build system is something I need to cover much more thoroughly, but is something that will take a long time.
It is probably a matter of terminology. For some reason different languages see fit to give the same thing different names.
A union is a type that can be one of several different things. In C unions, there is no built-in way to tell which of those things any given union instance is at any given moment, which can lead to code assuming it is one thing when it is actually another. Tagged unions carry an enum with that that tells you which thing they are right now. Zig will not let you work with a tagged union's value unless you switch on the enum (tag) so you know what you're working with.
> * The same way the Zig compiler is awesome the underlying build file you often wanna write is just horribly documented. I don't understand half of it and it changes a lot. Andrew should really politely ask people on the internet to take down old repos and blog entries. Please document the build system and build file writing better.
Agree wholeheartedly. I've never even bothered to use zig build in years of working with zig because of it. Granted, I make it a rule to rethink what I'm doing if I actually need a complicated set of build steps, but sill.
The language itself is fantastic once you get a decent grasp of it, which you'll probably achieve by reading the stdlib source to get a feel for what you need to do.
I've been using it to build stuff on my Pi Zero. Still hit a few snags with cross compilation and C interop, but it's been a pleasure to write. I'm definitely keeping an eye on it as a good alternative to getting into Rust.
Another upside with Zig coming from the embedded world is Zigs idea of doing async/await - since you define the building blocks yourself, it’s really easy to create an async/await-implementation e.g. on top of epoll, but for those times when your hacking on bare metal, you can just write an implementation which fits that particular hardware. It’s really, really good.
What you're asking is absolutely reasonable and I agree that these are things that should exist. The blocker (for the things that I control / can contribute to) is mostly effort and resulting value.
I considered the idea of working on a book that would do a proper introduction. It's something that would be useful, without a doubt, but the problem is that it would take a lot of effort and time (given my current skillset) and it would take away from other possibilities that in my estimate would be more cost-effective for the project.
So the TLDR is that we're genuinely thinking constantly of what's the next best move to make and, given the situation the project is right now, we think other things have to take priority. Of course we could be making a wrong estimate, so we're open to discussing it, but we have to follow the path of least resistance, which means making temporary compromises.
My bet is that if we play our cards well there will be enough skilled communicators interested in writing Zig programming manuals, we just have to get there first :)
I also want one day to write a book on comptime, hopefully it won't take too long!
This is the thing I love so much and if you guys combine this absolutely amazing attitude with some professional marketing I just see a bright, bright future for the Zig language.
I tried all the so called C replacements, and especially Rust. The Zig language is the only approach where one does not need an IQ of a 130 to learn it. Just please you guys do everything to not vanish into a absolute niche like D did, because D was and in my opinion still is such a great candidate/language, they just should have done better marketing.
I would be looking forward for your book and would be the very first one to buy it!!! Also, can I donate to ziglearn, Zig Showtime and/or the Zig Foundation?
In my opinion Linus should think about letting Zig into the kernel and not Rust :D. Maybe one day you guys will also achieve that.
Thank you again, we try :)
If you want to support the ZSF, here you can find all the information you need: https://ziglang.org/zsf/ I'm the one answering mails to donations@ziglang.org, btw.
For ziglearn and Zig Showtime, I guess you should check our respective GitHub profiles.
Zig offers a radical design. It seeks to be as simple as C — which is particularly important in low-level programming for both portability [1] and humans and machine analysis — while also giving you safety and high expressivity. Obviously, radical design means doing things differently.
Zig rejects any kind of implicitness; all calls must appear as calls. This means no operator overloading, no destructors, and no magical traits. It does so, however, without giving up on expressivity by using other mechanisms.
All low-level programming languages suffer from low abstraction. That comes with the territory. By that I mean that implementation details (especially around memory management) are hard to hide. Changing those details in some component often require changing the clients of that component as well. But C++ and Rust have a design philosophy that tries to hide this intrinsic quality of low-level programming by making the final code appear on the page as if it has abstraction capabilities similar to high-level languages. Of course, that illusion breaks as soon as you try to change code, and it's debatable whether this design helps or harms program comprehension. Zig rejects the C++ philosophy in favour of a brand new, and pretty revolutionary one, that reimagines how low-level programming is done. Unlike Rust, Zig isn't a cleaned-up C++ with a few extra tricks, but it isn't a new C, either. It's something completely different.
You might prefer Zig's design for this domain (as I do) or you might prefer the more traditional C++ design, but the great thing is that Zig is so simple and easy to learn that it's easy to try and find out.
[1]: Consider what it would take to port C++ (or a C++-like language) to new microcontroller you build. You would either need to port LLVM or an extremely complex compiler — a huge undertaking. This is why C (well, there's a tiny bit of Ada, too) still reigns supreme even in domains where correctness is of utmost importance: https://youtu.be/uqan23518Yc?t=632
The more I use Rust the more I am convinced I can write high level performant code. I mean it's ridiculous that sometimes I forget I am writing Rust and not Scala!!
As someone who does a lot of low-level development, before Zig I didn't think any approach other than that of C or that of C++ was even possible. I don't know if Zig will fulfil its promise, but its radical design, that's unlike anything we've ever seen, sure offers a fresh perspective on things.
As to static guarantees -- they are never the point; they are a means to an end: writing more correct programs. That goal is just as valued by Zig as it is by Rust, Zig just tries to achieve it differently. Which achieves it better? It's hard to know right now. I have little doubt that Rust could make things that are today written in C++ safer, but I have serious doubts whether it would be adopted in truly safety-critical domains, where C is king. I think Zig could be.
Procedural macros are also somewhat insane in many ways.
It seeks too, but fails. Comparing to really-simple C, it's full of arcane stuff.
> Zig rejects any kind of implicitness; all calls must appear as calls.
We already have that in C.
> Of course, that illusion breaks as soon as you try to change code
That's one of the traits of Zig too it seems. My favorite example of Zig's poor design is following case:
Suppose you have a function call:
collectNoInline(gc);
And you want to annotate it for being never-inlined (call-site level annotation for "always inline" and "never inline" is a customary enough task in low-level programming). So, in Zig, annotated call transforms too: @call(.{ .modifier = .never_inline }, collectNoInline, .{gc});
Ref: https://ziglang.org/documentation/master/#callI'm sorry, but that's total nonsense. Shows that not enough good faith went into Zig design. Even in C, that could be syntactically annotated as:
/*pragma:noinline*/
collectNoInline(gc);I think it's quite the opposite. Don't forget that C also has macros and a lot of arcane undefined behaviour. I don't know if Zig is as simple as C -- it doesn't have macros but does have, say, slices and comptime -- but it's also much safer and much more expressive. Overall, it's a very simple language, that's very expressive and also quite safe.
> That's one of the traits of Zig too it seems.
Absolutely! It's a feature of all low-level languages. Zig, however, unlike C++ and Rust, doesn't try to waste its complexity budget on making it seem like a high-level language when you just look at the code on the page (and it has other downsides, too, besides language complexity).
> I'm sorry, but that's total nonsense. Shows that not enough good faith went into Zig design. Even in C, that could be syntactically annotated as:
And I'm sorry, too, but I would say it's an example of Zig's exceptionally great design at this stage. If at some point it turns out that adding a new kind of syntax element here is worthwhile, it can always be added later. When in doubt -- leave it out. You never know when your complexity budget is best spent, and if you already have a general means of doing something without a new syntactic category, it's best to wait and see.
The status quo for iterators is this:
var it = getSomeIterable();
while (it.next()) |item| {
...
}
IMO it's "good but not great" (not great because it adds a var and the variable pollutes the outer scope). But the alternative is a bit of a pandora's box.I understand where it's coming from, but having something like "for (i32 i in [0,n[)" would be so much nicer in my opinion.
You can do:
var i: usize = 0;
while (i < 10) : (i += 1) {
...
}
or var i: usize = 0;
while (i < 10) {
defer i += 1;
...
}
although the two have slightly different semantics (the latter would increment even after a break; the former wouldn't).Talk about confusing, implicit syntax of Zig - there's no connection between "it.next()" and "|item|". It's implicit and you need to make it up. Compare that to other languages: "for item in it" or "while (item = it.next())".
The for loop payload syntax, where you can also give a name to the counter, is the only weirdness with it.
There is an example here for a kind of iterator.
Why is this ".{x}" and not just "x"?
This syntax is used tens of times in the following code snippets but never explained.
This is the kind of information that your tutorial needs to contain, because it's radically different from C and other languages, and this is exactly the kind of information that readers will be looking for: "How different is Zig from C and why should I care?".
Why is just "x" not allowed? What does ".{x}" actually mean?
It all makes a lot more sense after understanding Zig's comptime features:
https://ziglang.org/documentation/master/#comptime
The end of the comptime section also explains how string formatting works that way.
- parsing command line arguments
- logging (loglevels, files, stdout/stderr, etc.)
- talking to a restful service via HTTP
Thanks in advance!
https://ziglearn.org/chapter-2/#iterators
I don't think that going further into parsing is in scope. std.log is something that definitely needs to be covered. HTTP, I'm not sure about as it requires a lot of extra machinery outside of the standard library and these things aren't mature yet.
https://ziglang.org/documentation/master/
And the (fairly new, and still a bit thin) std library documentation
https://ziglang.org/documentation/master/std/#std
...gives a good enough rundown to start writing real-world code if you're coming from another C-like programming language.
Zig's std lib documentation will keep getting better. In the meantime, the std lib code itself is so well written, it's worth a read, even coming from another language, and even if you have no intention to learn Zig. I found it easy to read and was impressed by the code structure and quality of the design.
Of course, that's not to suggest that code is documentation, but I've learned alot about improving my programming in general, just by reading Zig's std lib.
That doesn't seem to be true. The example below this sentence errors because the function foo being used doesn't exist, not because the variable is undefined. A proper example [1] shows that Zig will happily use uninitialized memory here:
x: -1431655766
[1]: https://godbolt.org/z/36j4ab> [Once a variable is set to undefined], it is no longer possible to detect that the value is undefined. undefined means the value could be anything, even something that is nonsense according to the type. Translated into English, undefined means "Not a meaningful value. Using this value would be a bug. The value will be unused, or overwritten before being used."
> In Debug mode, Zig writes 0xaa bytes to undefined memory. This is to catch bugs early, and to help detect use of undefined memory in a debugger.
An incremental compilation feature is coming to the self-hosted compiler: https://kristoff.it/blog/zig-new-relationship-llvm/
The @import method is only for "importing" C headers with declarations and have them automatically converted to Zig interface declarations (so in most cases you don't need manually maintained language bindings). For compiling the associated C soure files, Zig has a builtin C compiler.
It's named "Futureproof": https://www.mattkeeter.com/projects/futureproof/
We're serious in the sense of very much alpha, and with a long way to go, hopefully intersecting with Zig's stability program in the next year or so, but we have some demos and benchmarks in there of using Zig for io_uring. Zig's std lib already has io_uring helpers based on liburing's design, which we contributed.
We would have gone with C for its ABI, OOM-safety and control over memory layout, but considered Zig ready enough given our own medium term timeline, and the developer velocity and safety is already paying off. We also wanted a fantastic compiler, which Zig already provides. I personally wouldn't go back to C for a new project like this.
https://github.com/floooh/pacman.zig
...and before that I did the same in C99 (might be useful for comparing the languages):
https://github.com/floooh/pacman.c
Disclaimer: I'm not a Zig expert at all, and the project doesn't really require most Zig features that differ from C. But I think writing small and "for-fun" projects like this is important for getting used to a language. I think one of Zig's big qualities is that it is so straightforward, after a few hundred lines you hardly have to look up things in the language documentation anymore.
Anyone who has dug into these care to comment about the pros and cons of each?
rust: more like a safe c++, you can get all the performance of c or c++ with the memory safety of a garbage collected language, as well as data race safety and nulls do bot exist. downsides are it can be a hard to learn paradigm to satisfy the compile time memory checks, and it is slower to compile
nim: sort of like a statically typed python. fun syntax and features, compiles to C, quickly. has in the past used garbage collection but a new reference counting mechanism has been introduced lately.
If anyone has an idea about the (A) relative stability of the languages, and (B) the number of libraries/packages for things you don't want to write yourself, that'd be great.
Note:
> has in the past used garbage collection but a new reference counting mechanism has been introduced lately.
Reference counting is a kind of garbage collection. It's often faster than the "hello world" of gc, namely mark and sweep, but it has its own challenges.
Anyway, I don't think production readiness of a language that hasn't reached 1.0 really matters.
It might be better to publish a lot of stuff about a single topic, where it can attract interested groups and build enough that it actually proves the merits of the language.
Edit: punctuation
```
std.debug.print("hello world!\n", .{});
```that kind of extra typing is what turn me off to be very honest, other than that, zig seems like C and Swift had a baby, pretty nice
another thing:
```
const LikeAnObject = struct{
value: i32,
fn print(self: *LikeAnObject) void {
std.debug.print("value: {}\n", .{self.value});
}
};```
Why don't make the self: *LikeAnObject implicit?
Again, this focus on extra typing only just add noise in my opinion, function is already wrapped inside the struct, i feel like it HAS to be implicit
-- EDIT --
One last thing:
```
for (array) | value | {
std.debug.print("array {}\n", .{value});
}
```Not a fan of the | | syntax, it doesn't feel natural
```
for (value in array)
```Here it is pretty clear what it does
-- EDIT 2 --
```
const std = @import("std");
std.debug.print("hello\n", .{});
```
is import the right word here? feels like it should be ``use`` since you'll use them this way: ``std.debug.print``
``import`` would be to make all the types directly visible and use this way: ``debug.print``
The || syntax is used elsewhere in zig, if statements, catch, switch, etc.
There's no requirement for a function inside a struct to act on the contents of structs, so it's reasonable to use structs as namespaces. This is what is happening when you @import, for example. The imported file becomes a struct.
This is quite different from a lot of other PLs, but it is pleasantly consistent when you get used to it.
There is a usingnamespace keyword to make a structs public contents spill out into the current scope. It's to be used sparingly.
Edit: I'm wrong! It's an anonymous struct with number fields, not an anonymous array.
also why ask for a parameter when it is not needed? print vs printf in C
Consider the above code without it:
std.debug.print("hello world!\n", struct{}{});
Now add a value: std.debug.print("{}!\n", struct{string: []const u8}{ .string = "hello world"});
Quite unwieldy. Zig used to have variadic functions and it was difficult to work with, complicated metaprogramming, and made how things work less obvious during reading. It was also pretty much only ever used for the "print" function.It's compile-time checked. The example shows a compile time error when the struct fields are not completed by the anonymous struct
Edit: also, the print stuff, I feel that’s in line with the Zig Zen - make the language simple to understand. Now the print function has a very clear type. Otherwise you need a “smart” print function (like Rust does with a macro or C does with varargs). Easier to understand, not easier to type.
Why its not int64, int32, unsigned_int32, vec, function for all language, but inventors have to change these to u64, i64, fn...etc?
Languages have many competing goals. It shouldn't take long to get used to u64 over, e.g., unsigned_int64, and brevity is valuable in its own right. Too many wasted characters can obscure the flow of a program and make it slower to read and understand.
Is it the right choice? I could be persuaded either way. I know it's one I've personally made before, choosing rebindings like i256 and cmpeq8 when doing a lot of bit-twiddly vector code.
Having said that, less typing and clutter are also beneficial, so it's really a net natural debate.
Personally I prefer it, mostly for subjective reasons but I think it makes sense - in the case of Rust it was the easiest syntactic novelty to get used to, things like lifetime annotations are a different beast.
"i32" and "u32" are used because they are short (and used often). They are just typedef away in C and are used ~forever, did you look at Linux kernel for example?
But I'm with you on the general sentiment - beyond trivial, lexical things like type names (which almost any language allows you to redefine anyway), Zig appears to have strong NIH mentality in regard to the syntax. Trying to replace C, but go out of their way trying to invent syntax just to be different from it and most other things too.
And a lot of people appear to notice and pay attention to this, as the discussion here shows.
Jumping thru hoops is what Zig seems to choose with its unorthodox, different-just-to-be-different syntax. I wonder, how many will want to jump with it?
Did zig run over your dog or something? You seem to be particularly hostile in your comments about it. As someone who has participated in discussions about zig syntax for years, I can assure you that a significant amount of thought and consideration goes into these choices. It is not "different-just-to-be-different". In fact, the very syntax being complained about is derived from other languages!