277 points · by AndyKelley · 7y ago · 138 comments
When you click "Download & Documentation" there's a link under the headline "master" to the long-form documentation which has some examples: https://ziglang.org/documentation/master/
Edit: also found a blog post with a nice introduction: https://andrewkelley.me/post/intro-to-zig.html and an examples directory: https://github.com/ziglang/zig/tree/master/example
Interesting to see how the language has evolved away from using "%" in the original Hello world:
const std = @import("std");
pub fn main(args: [][]u8) -> %void {
// Print "Hello World!", and believe that no errors will happen
std.io.stdout.printf("Hello World!\n") %% unreachable{};
// Short version:
%%std.io.stdout.printf("Hi!\n");
}
Compared to the newer version : const std = @import("std");
pub fn main() !void {
// If this program is run without stdout attached, exit with an error.
const stdout_file = try std.io.getStdOut();
// If this program encounters pipe failure when printing to stdout, exit
// with an error.
try stdout_file.write("Hello, world!\n");
}Succinct examples on a clean page, no fluff.
I love seeing all the progress with Zig, V, Muon, and Rust. All these languages are potentially-better systems languages than C/C++, with better safety, better definitions, and better semantics. Zig has an explicit goal to be better than C and to replace it.
C might die, but there's no replacing it. Sorry.
The hard part is build tool compatibility but I think there are a lot of good ideas being worked on actively, Zig and Rust being two examples of advanced programatic control over the build process. With a reasonable linker, it should be possible to combine these and more languages today.
An interesting counter example to the binary interface compatibility story has been Go, which seems to let cgo become less and less functional in each release. The pressure to keep everything in Go is an interesting trade-off. I wonder if certain kinds of systems will be paying for this lock-in later down the line while other languages give much easier ways to gradually evolve and reuse code or adopt libraries from multiple communities removing the need to do yet-another-rewrite in language X kinds of projects. Or perhaps this kind of interoperation is overrated? Time will tell.
That already works, not a hypothetical. I can write, right now, a zig function, call it from rust, slap the whole thing into a library and wrap it with d. It hasn't taken the world by storm because these languages provide support the system c abi and calling convention, but do not embrace it. If I write a fancy templated function in zig, d, or rust, the name mangling, type-information, templating, maybe even call conventions -- are all different. This is why I have been and continue to be disappointed that things like COM or the jvm or cli aren't more popular, because they actually work that way. I can write, right now a clojure function, call it from java and then pass it into kotlin. Effortlessly, it's just an import away. Sure there are, for example, stdlib conflicts in scala but overall it's a much more frictionless experience. The problem? COM is windows-specific, jvm and cli are managed runtimes and people don't like managed runtimes.
Another place I look for a solution is racket, but again it wants to manage too much of the runtime to be practical. What zig is doing with the build system is great, the fact that the build script is actually a fully customizable script means it has a much better chance of taking off, but until I can import a jai module from d and call it in zig, we're gonna have problems.
EDIT: something which possibly almost could have had a good chance of pulling this off is llvm. Except that llvm comes too late in the compilation process to be used to resolve imports and symbols. Something like libclang, maybe, except not specific to c and c++.
Same applies on Android, where using a Java based library, even if stuck on their Java 6 - 8 world is much more desireable than having to deal with NDK and JNI boilerplate.
Likewise IBM and Unisys mainframes make use of their language environments instead of C based ABIs.
Zig and Jai aren't going anywhere. Zig appears to be a largely single contibutor (https://github.com/ziglang/zig/graphs/contributors the creator has < 2/3 of commits). Jai does not have a public compiler and is not likely to get a public release anytime soon.
As for rust we don't know yet how big of a chunk of marketshare it will take from new c and c++ code.
Not many people still use c code for "everything", most have already switched.
Aside from starting Zig as his personal project, Zig is also Andrew's job now. As far as I'm aware that is not true of any other contributor, so it makes sense he'd have the lion's share of contributions.
That's a good thing. The less contributors, the better the project usually.
Regardless, V lang is another data point that something besides C is a possibility with the modern tools that we have available to us. Whether or not it pans out is almost immaterial. Just the fact that so many people are finding some sort of success or making some sort of progress in this space is enough for me to continue to watch for any new progress in the C competitors.
There's still a lot of work to do, but the language is going to be open-sourced very soon in early June.
No they are not. C++ has spent decades building "a better C/C++". Any language that ignores those lessons and takes the stance of "learning C++ is too hard, let's go shopping" is doomed to fail.
<rant> For all the time and work poured into C++, it has remarkably little to show over plain old C99.
Some of those new "better C" languages are the work of individuals and very small teams, yet they are able to build more progressive "better C" languages than C++ can ever be because it is held back by the need for backward compatibility for 'failed features' and 'design-by-committee'.
If all that ever comes out of those small 'better C' languages is some sort of consensus of which core-set of features actually makes a 'better C', than they have already contributed more to programming language development than C++. </rant>
Exactly. I think of it as a path-finding problem. C was obviously not where people wanted to be. As with any path-finding problem, it's possible to make a wrong turn. Often, attempts to recover without backtracking only make things worse. I contend that C++ has done exactly this. They're at point where a mature, reasonable person would admit their error and backtrack until a better path can be found.
I doubt that many of C++'s critics are arguing from ignorance or afraid of complexity. More often, they're objecting to spurious complexity because they know how to do better. I've written compilers, and they're not even close to being the most complex things I've written. It's not so much "let's go shopping" as "let's return this defective merchandise" and build something that works. It's only the lemmings who insist on rushing further down the wrong path. "Turning around is hard; maybe if I get enough others to come with me they'll break my fall."
- RAII
- exceptions
- classes and objects
- inheritance
- templates
- the STL
C++ is strictly better than C when wielded correctly.
If there's one truth I've learned in my decades of dealing with computers, it's that you can't beat C at being C.
Before now, I'd never heard of Zig in particular, but I can think of several other languages that have tried or are currently trying. A lot of people seem to think they can make something a little better than C, in some ways, and that will be enough. I doubt that even C18 itself, if it were invented from scratch today, would be able to unseat another systems programming language.
Everybody forgot about Worse-is-Better: "Unix and C are the ultimate computer viruses". Any language which isn't more 'viral' than C (in terms of being ported, and attracting users) has no chance. You're starting tiny, and growing less quickly.
Have you ever seen a language that has made a serious attempt?
The last few years, the only significant one I know of is Rust. But it's not really a C replacement. C is essentially fancy assembly. Rust is conceptually quite advanced.
Zig is one of very few languages I've seen that makes a serious attempt at being a better C. No garbage collection, no fancy borrowing checker, but quite a few improvements/features that actually matter to low-level/embedded programming.
My use-case is microcontrollers, and I've tried a few different new languages for fun. Zig is the first one where I actually came out of it wanting to use it for real. The only problem is it's still not finished.
It's not obvious what needs to come next, which is the only reason that C is still here. Most likely several languages are needed to fully replace it. And our industry is starting to feel that out now.
D, Go, Rust, Jai, Zig, P, C# low level primitives. Things are changing. Even C++ seems to want to be a different language with some of it's latest developments.
Their sin was not being bundled with an OS, originally distributed with source code by a symbolic price.
I don't really want to restart a flame war that was extinguished decades ago but Kernighan's critique of Pascal (http://www.lysator.liu.se/c/bwk-on-pascal.html) is an interesting read today - if only because it reminds me how much simpler things were back then - no mention of memory safety or multi-threading.
I have no knowledge of Object Pascal and Modula-2, so won't comment.
Was not abandoned, it was rebranded to “Delphi” and is still around.
I think it's fine to have aspirational but unrealistic goals.
> If there's one truth I've learned in my decades of dealing with computers, it's that you can't beat C at being C.
You can't, but as the realm of computing expands, it makes space for new languages. There's a lot of room in the space adjacent to C. We have embeddable languages -- schemes, lua, even Python to some extent. We have languages like Zig, Rust, and D, that can compile to object files that look as if they came from C. And we have other languages that generate C, like lisps and ocaml have done for 20 years now.
C doesn't have to be a language anybody writes, to be a language that everybody uses.
Some of my personal highlights:
- clean syntax
- comptime (as explicit and simple as it should be)
- reflection
- minimal/no external dependencies
- single threaded mode (instead of taking cuts at runtime)
- concise and explicit error handling
- build-in build system
- amazing C interop
...
Good sample code can also be found in the standard library, and it has the benefit of being up to date with with language.
Thanks Andy!
- "zig is also a C compiler" . Flag-compatible with clang, and with integration with zig's buildsystem you get cached build artifacts.
- Cross compile for a boatload of architectures + musl or glibc - in a ~30Mb compressed package
Another small annoyance was Zig rejecting \r in line endings. Thankfully, I'm using Emacs so it only took me 15 minutes to google the right fix. But it felt a little "gratuitous" if you know what I mean.
The code itself should be up to date for most, but I'm aware of a few examples than need touch-ups. Unfortunately there is a bit more boilerplate compared to other languages for some simple tasks, since Zig requires you to be quite explicit about things (e.g. i/o, memory allocation).
Regarding the rejection of '\r', there is the intention for `zig fmt` to handle these minor issues and reformat code as needed which hopefully reduces this barrier. There was a long issue regarding hard tabs with discussion here: https://github.com/ziglang/zig/issues/544
It's been a real pleasure seeing Zig grow, hopefully it can fill that niche for a high performance, portable, modern language that isn't filled with OOP cruft
https://ziglang.org/download/0.4.0/release-notes.html#Build-...
I've been playing around with embedding sqlite for a Rust project and checking the C into the source tree made sense there too.
Zig claims very proudly it is about clarity but shortly into reading through the documentation I already found this extremely surprising:
"Multiline string literals have no escapes and can span across multiple lines. To start a multiline string literal, use the \\ token. Just like a comment, the string literal goes until the end of the line."
I could not have tried to make a more confusing token for multiline string literals if I tried. The difference between a string literal and comments is literally whether or not the lines are preceded by an open =.
Well comments use forward slash (//) and string literals use backslash (\\)
Python has an even closer relationship between comments and string literals: its multiline comments are just string literals that get never used.
That's not entirely true. A literal string immediately following a class or function is inspectable via its __doc__ member.
E.g. class Foo: "I am Foo." def bar(self): "I am Foo.bar"
Foo.__doc__ will have "I am Foo.", and Foo.bar.__doc__ will have "I am Foo.bar".
This is rarely used programattically, but at least one standard module uses this for running tests: doctest
Edit: not sure why it's not formatting correctly, as I am spacing the code a 4 space indent, but at least on my phone, it is not properly formatting as code. I apologize.
Why this algo in particular? Is this a security feature? I suppose wrt "Reflections On Trusting Trust" it may be. But if it didn't need to be secure it could probably be a lot faster (assuming this is a critical path for cache hits).
I haven't tested the performance of any other algorithms, but that's a completely swappable component. I'm sure the hash function will be swapped with a different one before 1.0.0 is done.
It would be more fair to not even mention them as supported _at all_, or at the very least to document them as Tier 4.
I haven't played with Zig but it looks a lot more appealing than e.g. Rust to me.
In the end though, I'll prefer plain old C (C99 or C11).
const std = @import("std");
* pointless semicolon* pointless "@"
* seemingly pointless "const" (can you define a mutable import?)
* unnecessary verbosity defining an identifier for the import when there's almost never a need for naming it differently (i.e. it should default to "const std" if you just type "import 'std'"...
I like Go because it avoids pointless verbosity most of the time.
Except for all those times you had to manually write err != nil
There might be very good reasons for each of those things, but it's hard to say without delving into it some more.
but then you've just imported all of std into your own namespace. (probably not using the correct terminology here).
At any rate the const indicates you're not changing, and the std is the name given to the root of the hierarchy for importing "std" into.
Sure go lets you do this too, but has shorthand.
import "fmt"
can also be done as import fmt "fmt"
but why would you do that?The go equivalent of zig's "use" is
import . "fmt"
"." means "the current working directory" on unix so it's familiar to folks in that sense perhaps. Principle of least surprise is nice when the syntax is terse.Still, I think I like zig. I feel like I want to try to write something non-trivial with it when I look at the features.
I've already done that a few times with Go, and I enjoy that too.
It's noticeable that there are a lot of differences, and some things seem to have been deliberately made different (even if they are in essence very similar and only syntactically different), so for me it looks a bit odd that most references to Rust on his blog nowadays are of adversarial nature (ie, "look how better we are than Rust").
Last, but not least, it also doesn't help with the big picture that the one continuously posting links about Zig here is just self-promoting their own creation...
Anyway, just my $0.02
> the one continuously posting links about Zig here is just self-promoting their own creation
Nothing wrong with that. If their creation fails to excite people, there won't be any conversation, it won't make it to the first page, etc.