22 ms·
Zig in 30 Minutes
- sunsetSamurai 6y agois there something like this for scala?
- johnisgood 6y agoDoes anyone use Zig for production?
- dhruvdh 6y agoI don't think Zig is production-ready, if someone is using it there must be a special case where they think it makes sense. Anyway, I don't think production readiness of a language that hasn't reached 1.0 really matters.
- jorangreef 6y agoJens Goldberg did a fantastic talk on Zig in Production: https://www.youtube.com/watch?v=124wdTckHNY https://www.youtube.com/watch?v=124wdTckHNY
- deleted 6y ago[deleted]
- nynx 6y agoThere are some very clever concepts in Zig (I like the fact that types are compile time values), but the language doesn't seem to be as carefully designed as some others. For example, for-loops only work on a few, blessed types.
- dhruvdh 6y agohttps://www.nmichaels.org/zig/interfaces.html https://www.nmichaels.org/zig/interfaces.html There is an example here for a kind of iterator.
- dbandstra 6y agoI wouldn't call that careless. So far, proposals to extend the for-loop have not passed the cost/benefit test. I think supporting iterators would require something like magic-methods, which so far are not a thing in Zig (language syntax doesn't interact with userland code). 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.
- Leherenn 6y agoHonestly, I know it's minor, but when I tried Zig the fact I couldn't do the classic for loop to do a "for (int i = 0; i < n; ++i)" was quite annoying. It pollutes the scope, so you need to add scope braces every time, and I find it's much easier to forget the ++i at the end of the while loop. 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.
- pron 6y ago> and I find it's much easier to forget the ++i at the end of the while loop. 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).
- gilmi 6y agoThis is very nice! I think it would be more useful if it talked about the memory model, heap allocations and pointers which I'm guessing is pretty important for anything non trivial.
- dnautics 6y agothat's fair! I also didn't go into async/stuff. I'll put a note at the bottom.
- andi999 6y agoI am always interested in zig, but these mini tutorials don't give you anything beyond what simple C does (apart from the exceptions). The full docs do not have enough examples (last time I checked). I would really like something like K&R for zig.
- flohofwoe 6y agoIMHO the official documentation: https://ziglang.org/documentation/master/ https://ziglang.org/documentation/master/ And the (fairly new, and still a bit thin) std library documentation https://ziglang.org/documentation/master/std/#std 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.
- andi999 6y agoIn my opinion it doesn't. I Shows all the features/keywords but it doesn't teach you how to use it properly. I presume you didn't study K&R?
- flohofwoe 6y agoI've read K&R Second Edition, but only after I already learned C through other means. From that PoV, K&R is an interesting look into the design rationale of C against its historic background, but since it is stuck at C89 I wouldn't recommend it today to learn the language TBH :)
- jorangreef 6y agoTo be fair, K&R (as awesome as it is) also doesn't cover things like epoll or io_uring? And then again, K&R's definitely not a half hour read. 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.
- andi999 6y agoHow do you do modules in zig? Like when you have your code in 5 C files and link the obj? How to do that?
- dnautics 6y ago@import can take a path. I guess i should put that in there. The details are pretty cool, the imported file becomes a struct!
- pjmlp 6y agoJust like JavaScript modules, kind of.
- andi999 6y agoSo are they all recompiled? What about compilation/linking time? Or is this not a concern since the zig compiler is fast?
- flohofwoe 6y agoC source files are only compiled on full rebuilds, or when the C source file changes, just like in regular C projects. You can distribute precompiled libraries, but I think given that one of Zigs prominent features is simple cross-compilation to all sorts of platforms, compiling from source is preferred. 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.
- andi999 6y agoI think you misunderstood my question. I am not (in this question) interested in C or C interopability of zig, but how to structure larger zig project (how zig thinks this should be handled)
- 6y ago
- hungnv 6y agoI wish all language as same syntax, no matter whats its implementation, no matter it has cool feature or not. So new comer will get use to it faster. Why its not int64, int32, unsigned_int32, vec, function for all language, but inventors have to change these to u64, i64, fn...etc?
- Santosh83 6y agoSyntax has a heavy influence on function, so if all languages had very similar syntax, they couldn't be ideologically diverse without jumping through ridiculous hoops.
- pfalcon 6y ago> couldn't be ideologically diverse without jumping through ridiculous hoops. 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?
- AnIdiotOnTheNet 6y ago> Jumping thru hoops is what Zig seems to choose with its unorthodox, different-just-to-be-different syntax. 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!
- pfalcon 6y agoNo, I'm adept of (anti)survivorship bias. In other words, I like to study mistakes. And Zig offers a great field of study in that regard, as many issues are seen with a naked eye (i.e. even to casual passers-by).
- didibus 6y ago
- hota_mazi 6y ago> std.debug.print("foo param: {}\n", .{x}); Why is this ".{x}" and not just "x"? This syntax is used tens of times in the following code snippets but never explained.
- dnautics 6y agoThanks for the catch! It's an anonymous array. Later down there is a place where there are two sets of brackets in the print string, and the so the anonymous array passed to it has to have two items (the string is analyzed and the correct size of the array is compile-time checked, no stack drilling here).
- hota_mazi 6y agoDoes this mean that "print" only takes two arguments, and the second argument has to be an array? 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?".
- dnautics 6y agoYep! The document has now been updated. I might have been blind to it because my daily driver is Elixir, and it does "basically the same thing" with keyword arguments.
- hota_mazi 6y agoI totally understand why being immersed in something might make you lose perspective, but keeping this perspective is what differentiates a decent language designer from a great one. Does this mean that zig doesn't support varargs? If not, why not? Again, another question that a lot of people coming to your page will be asking themselves, please don't take that as a criticism, just candid feedback to help you make your article better.
- zamadatix 6y agoSomething like this for build.zig would be amazing, https://ziglang.org/documentation/master/#Zig-Build-System https://ziglang.org/documentation/master/#Zig-Build-System is pretty light on the details based on what I've seen in the wild projects do.
- WhoCaresLies 6y agowhy do you pass an empty struct ``` 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``
- WhoCaresLies 6y ago-2 points for giving my impression???? why??? is there an agenda i am missing?
- pfalcon 6y agoIt's fun to see any comment talking about issues with Zig gets downvoted here ;-). And there're many indeed. The biggest one is NIH mentality of course.
- galfarragem 6y agoNice work. It would be great if you could add a Zig page on https://learnxinyminutes.com https://learnxinyminutes.com.
- mouvedia 6y agoI am already working on it. https://github.com/adambard/learnxinyminutes-docs/issues/4005 https://github.com/adambard/learnxinyminutes-docs/issues/400...
- emptyparadise 6y agoInteresting. Some unusual syntax in there, with for loops and arrays, for example. What are some more serious projects made with Zig?
- flohofwoe 6y agoNot "serious" at all but I wrote a Pacman clone over the holidays as an excercise and test for my cross-platform C header bindings: https://github.com/floooh/pacman.zig 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 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.
- emptyparadise 6y agoThanks! I was using "serious" very loosely, more in a sense of wanting to see the language in action beyond demonstrations and examples.
- jorangreef 6y agoTigerBeetle (an accounting database for a high throughput payments switch): https://github.com/coilhq/tigerbeetle https://github.com/coilhq/tigerbeetle 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.
- mkeeter 6y ago
- jeff-davis 6y agoLanguages, much like startups, are usually successful by focusing in one area and growing that first. The "$LANG in 30 minutes" format seems to play more to a general audience, which I fear will lead to a whole lot of people saying that it looks neat, and maybe they will get to it later. 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.
- mangamadaiyan 6y agoIf I understand it correctly, the intent of this format is to let the reader pick up enough of the language to be able to read code without getting frustrated. I think this is a good goal, and there is indeed some value in it. These languages are complex enough that articles in this vein are useful. They are not, and -cannot- should not, replace documentation and tutorials. Edit: punctuation
- overflyer 6y agoHey man, first of all thanks a lot for you efforts. This and ziglearn.org are just great as a starting point. 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.
- friend-monoid 6y agoI remember doing some basic IO using clib. There’s is a flag, like —link-clib or something. Then you can include header files as you would in C. I created a basic example a while ago doing some basic IO, epoll, timers, and linking in a C obj file, just to try out how to do embedded in zig. It’s really good. 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.
- 6y ago
- dejj 6y agoNice work! Can this be also on learnxinyminutes.com (https://github.com/adambard/learnxinyminutes-docs https://github.com/adambard/learnxinyminutes-docs) ?
- mouvedia 6y agohttps://news.ycombinator.com/item?id=25624133 https://news.ycombinator.com/item?id=25624133
- GordonS 6y agoI saw something similar for both Nim and Rust the other day, both of which I believe target the same space (safer alternative to C). Anyone who has dug into these care to comment about the pros and cons of each?
- gameswithgo 6y agoZig: a language that most people who like C but not C++ will probably love. simple and compiles fast and deals with undefined behavior and null more safely than C, easy c interop, no garbage collection 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.
- nimmer 6y agoNim is also as programmable as Lisp, and memory safe with automatic reference counting.
- chris_st 6y agoThanks, that's just the kind of comparison I was looking for. 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.
- mikewarot 6y agoThanks for summing it up, so now I know who Zig is targeted at, and it's not me. 8)
- paulsmith 6y ago
- NieDzejkob 6y ago> You can explicitly choose to leave it undefined if it will get set later, but zig will error if you try to use it. 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 https://godbolt.org/z/36j4ab
- dilap 6y agoYes, you're right. From the manual: > [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. https://ziglang.org/documentation/master/#undefined https://ziglang.org/documentation/master/#undefined