249 points · by dgellow · 6y ago · 352 comments
And that's a huge shame. Because in general I really liked using D.
I am not sure what to make of this pattern. At least the documentation should be more explicit about these Voldemort types. Documentation has other issues as well. The standard documentation generator doesn't cope well with version statements (conditional compilation), potentially skipping docs for stuff that wouldn't be compiled into a particular build variant.
fn map<U, T, F, I>(it: I) -> impl Iterator<Item=U>
where I: Iterator<Item=T>, U: From<T>
{
it.map(|t| From::from(t))
}
infinitely more readable than fn map<U, T, F, I>(it: I) -> auto
where I: Iterator<Item=T>, U: From<T>
{
it.map(|t| From::from(t))
}
The type signature of the first one clearly tells me that the return type is an `Iterator<U>`, even though the actual type cannot be named because of the anonymous closure.The second one leaves me guessing what the return type is.
If the actual type cannot be named, it is rarely the case that this is all there is to it. Usually, users are expected to use that type "somehow" (it is a `Range`?), and that means that there are some interfaces that these types implement.
For example, the return of map could provide indexing, or it could provide forward and backward iteration, or it might have methods that are completely unrelated to the type.
There is no good reasonable and non-confusing way to describe all the things map could return depending on the input. It's much better to just describe it conceptually in the human-readable docs, and let the person understand the result.
I'll note that just above the function map in D's source is the documentation. You just need a little more context, and it will describe what map returns in a much more (IMO) useful fashion than a return type that might be several lines long and consist of various static conditionals:
"The call map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range."
This is the difference between duck typing and generics.
Having auto is a boon for certain design aspects. As system level programming language D offers everything in betterC mode. Of course it can offer more. But a small community can do only so much.
edit: Looking at other answers, I think Range is probably not an interface like they exist in Java, but rather a pattern of behavior per templates in C++. Concepts are supposed to solve this problem in C++, but I don't know how well they actually do.
With highly generic functions, it's often not possible to know what they'll return without knowing what you'll call them with. Especially given that D functions like "map" and "reduce" tend to return special iterator types so that the compiler is able to smarty fuse them where possible. If D had concepts like C++20, you could probably describe them with something looking like:
template<class R>
concept __SimpleView = // exposition only
ranges::view<R> && ranges::range<const R> &&
std::same_as<std::ranges::iterator_t<R>, std::ranges::iterator_t<const R>> &&
std::same_as<std::ranges::sentinel_t<R>, std::ranges::sentinel_t<const R>>;
But at least for me that doesn't seem like it would be much more helpful than just reading the documentation, which states what the function returns, if not necessarily the type.Of course it is. Map's type is "(a -> b) -> [a] -> [b]". D just absolutely and completely failed here, despite this being a solved problem 40 years ago.
Ahh.. welcome to computer "science", the ever repeating cycle of 'inventions'
pragma(msg, T);
where T is any type will print the type to the screen during compilation. pragma(msg) will print all kinds of things, making it a very handy tool to visualize what is happening while compiling. I use it all the time.There is something so absurd about having "unnamed types" as an antipattern!
Another reason is the (ironically) dynamic nature of a return type. E.g.
auto whatDoesItReturn(int i)() { static if (i == 0) { return int.init; } else { return string.init; } }
Template code can do that quite easily and then you don't have a choice but to write auto as the return value.
What would be fantastic if the documentation could be given access to the the compiler's return type inference, so that it could document the auto returns with a little more info.
Another way useful approach would be to implement protocols like in swift, or traits like in scala/rust/others, signatures in ml, etc. Then you would be able to define the interface of what a function returns.
I agree with your point, but for the sake of the audience who doesn't know D I think this example is misleading, as one could take the "int i" parameter as a runtime one, while it's actually a compile time one (the equivalent of C++ non-type template parameter). If you instantiate the function with 0 as a compile-time parameter, it is a function that returns int; otherwise it's a function that returns string. It is never a function that can return int or string.
I still think the best option is let the author describe it in ddoc, as the semantic meaning can be much easier to convey that way.
If the docs are filled with this, then D is certainly coming off my list of langs to look at.
For functions that can return different types, I think interfaces or union types would be more helpful (not sure if D supports either though).
There's a wanting implementation of a sumtype in the standard library (https://dlang.org/phobos/std_variant.html#.Algebraic), and a much better one as a package: https://code.dlang.org/packages/sumtype
Most people will tell you, "oh just use auto, it makes the code more generic". That's sweet, except as soon as I want to pass it to another function, I need to have the concrete type. Like you, I usually just copy-paste the full type from the error message and move on.
for (Map.Entry<SomeLongType, AnotherLongType> x : someMap) {
final SomeLongType key = x.getKey();
final AnotherLongType value = x.getValue();
...
}
In the above code snippet, `var x` would have been very useful because the actual type just repeats information that can be found in the next two lines. Also, usually, I'll use more speaking names instead of `key` and `value`.But if the body of the loop just refers to `x.getKey()` and `x.getValue()`, without extracting them into local variables, then it makes sense to put the exact `Map.Entry` type into the loop header.
for (Map.Entry<SomeLongType, AnotherLongType> x : someMap) {
final var key = x.getKey();
final var value = x.getValue();
...
}
Is valid.It's 2020. Why couldn't things work like this, where one can open a window for a concrete type using templates, and it shows the code?
MyClass myVar = new MyClass()
is not DRY. It also makes it practical to use complicated structures out of generics/templates without killing the developer With<Deeply<Nested,Template>, Declarations>. MyClass myVar = something ? SomeFunction() || somethingThatMightBeASubClassOfMyClassOf course good tooling is still a big requirement, but I still think it's the best decision in the long-term: it's way easier to improve and change tools like IDEs (especially with LSP?), rather than the language itself.
Regarding explicit types in functions, you also don't always need them in languages such as OCaml. I feel that the answer to your criticism could be to just have "auto" also for function arguments, especially when you're just prototyping.
There are many cases where the type is clear however or irrelevant or in generic code is hard to express (thus depending on documentation/comments unless obvious) which would also be hard to read.
Could you please paste some example of a function that has a return value which is declared as auto?
https://dlang.org/phobos/std_algorithm_sorting.html#partitio...
The important line is
auto pieces = partition3(a, 4);
So, what's the type of pieces? The D standard library is written to be generic. And sure enough, that line of code will run. Where it turns into a problem is when you try to do something with it. If pieces is a range, there are certain things you can't do with it. Or maybe you can. Who knows. You'll never learn it from reading the documentation. I've been using D since 2013 and I still struggle with this at times. It's a valid complaint. (D's a great language, but is short on manpower to fix rough edges like this.)
Did you not see the Returns section from that link?
"Returns: A std.typecons.Tuple of the three resulting ranges. These ranges are slices of the original range."
Further note: If you just saw `std.typecons.Tuple!(typeof(Range.init[0 .. $]), typeof(Range.init[0 .. $]), typeof(Range.init[0 .. $]))` which is what would have to be written there instead of auto, would that make you feel better? Do you not have to read the documentation to figure out what the function does or what actually goes into those tuples?
In this (and the sibling pages in algorithm) nearly every entry is listed as either "template" or "auto" relhttps://dlang.org/phobos/std_algorithm_iteration.html
auto auto map(Range) (
Range r
)A range with each fun applied to all the elements. If there is more than one fun, the element type will be Tuple containing one element for each fun.
It wasn't. They probably didn't look into the more "generic" functions e.g. hofs and algorithms.
The vast majority of functions in https://dlang.org/phobos/std_algorithm_iteration.html returns "auto"
But sometimes auto is the best tool for the job, especially when writing wrapping types. In that case, yes, you have to read the documentation (and I mean what is written in the ddoc comments). But in many cases, you don't have to, because you recognize the pattern, or it's simply a wrap of the underlying type's function.
Whether that's really what you want and whether that is the best approach to solve the problem at hand is a matter of preference and the problem space.
It is also allows for a "gradual typing" approach that Dart 1 had.
At least that's what I understood.
In practice though, D codes fast and runs fast, as promised on the official site.
Anyways, var/auto is critical in some cases. C#'s LINQ, for example, would be very difficult to develop with if you had to manually figure out the type you were returning with long queries every time you wanted to restructure your query.
I wonder if the document could describe (in some regular way) how those auto types are constructed...from what input, with what operations?
(I see my snarky comment there got no reply.)
People like him tend to be biased about using auto because they write mostly libraries and generic ones at that (data structures, for instance).
In most code out there you actively avoid templates if possible, so that code is concrete, compiles faster and is easier to debug.
In general, this reduces to the principle that concrete is easier to reason about than abstract. The type signature of an unannotated function in a type inference system is maximally abstract, while (especially in practice) the signatures for functions that are manually annotated are more concrete if not fully concrete. There are still problems in non-type-inferred systems with programmers who try to be egregiously abstract, but these are fewer and farther between.
- "D as a Better C" (2017): https://dlang.org/blog/2017/08/23/d-as-a-better-c/
- "Vanquish Forever These Bugs That Blasted Your Kingdom" (2018): https://dlang.org/blog/2018/02/07/vanquish-forever-these-bug...
- "DasBetterC: Converting make.c to D" (2018): https://dlang.org/blog/2018/06/11/dasbetterc-converting-make...
Personally while D seems a great tool, I really keep running into situations where a language that lives on top of C/C++ is useful. So I’ve been trying out Nim for those use case, using the ARC GC which appears to work well for embedded. It’s deterministic but with move semantics for performance optimization. Interesting approach IMHO. But the biggest advantage is being able to directly interface with any C or C++ natively. D/Rust both seem to have difficulty being 100% onboard with C++ (for good reasons).
In any case here are the latest news on the subject,
"GTC 2020: Exterminating Buffer Overflows and Other Embarrassing Vulnerabilities with SPARK Ada on Tegra"
https://developer.nvidia.com/gtc/2020/video/s21122-vid
Another well know project that is now adopting Ada/SPARK is GenodeOS, https://genode.org/about/road-map
I thought one of the centerpieces of D was seamless c++ interop? Where does it fall down?
For libraries with a large API that can be an annoyance.
Only Active Oberon exposes non traced references, RAAI and a couple of other low level features that made it more complex to do systems programming in Oberon and Oberon-2, let alone Oberon-07.
- Units (modules) for separate compilation with strong type checking and not needing useless prefixes
- A proper string type
- Proper arrays with bounds checking, it has functions to retrieve upper and lower bounds
- Allows the definition of numeric ranges
- Enumerations are their own type, can be used as array indexes or data sets
- Support for sets
- Thanks to reference parameters there is less need to deal with pointers that might be invalid
- Already allows for a simplified way of doing Type Driven Development
- Supports type safe function pointers
- Supports single inheritance OOP with minimal RAII support for heap allocated objects
- Comes with a quite powerful OOP framework for TUI applications, Turbo Vision
- While it doesn't prevent use-after-free, it allows for memory regions that can be deallocated on one go
- Can map arrays to memory regions with bounds checking
- Besides inline assembly without UNIX's clusmy syntax, allows to use registers as variables
- If one really wants do do unsafe C style coding there are compiler pragmas to allow it and yes even pointer arithmetic and unsafe casts.
This in 1992, if I take a recent version of Delphi, FreePascal or Oxygene, there are even more bullet points.
I have a lot of respect for you and Andrei, and I think D deserves much more love than it gets.
I personally feel like there are too many options when it comes to D. Perhaps it would be good to double down on some combination of those options and make that widely known?
As a newcomer to D, I am exposed to GC/non-GC code, dmd/llvm compiler/gcc compiler, several debuggers, some BetterC option, etc. I don't know which toolchain is best, and I don't want to deal with the integration issues between them.
All of these options that exist are great, but the brand gets diluted. D seems to be the ideal thing: it's seemingly a better C++, and a better C, with a clean syntax like Java.
I trust it's a better C, but how do I know the combination of the D toolchain that I'm choosing is better than sticking with the devil I know already?
What I would love to see is an opinionated package spun off from D. One compiler, one debugger, one IDE, one standard library. Make my onboarding experience better and take the thinking out of assembling a D toolchain.
Every time I find myself thinking "maybe I should look into using D instead of C for this project", I spend a few hours with D, and then I get frustrated at all the options and I go back to the devil I know.
I truly wish I could be one day convinced that I can install D and I get a solid platform without weird moving parts.
IMO describing Rust as a "C replacement" is slightly off the mark because Rust's value proposition is very different from C. Rust is about giving you the best possible performance in a safe-by-default language. C is about giving you maximal control over memory, with a very thin layer of abstraction over the hardware.
C has traditionally been used in a lot of places where Rust's USPs add a lot of value -- for instance in kernel development -- simply because there wasn't a safe alternative. However I think there are other cases where the strengths of C still add value; for instance in game development you're largely trying to do high-throughput processing over large swaths of structured data, and Rust concepts which help safety like RAII just get in your way. Yes there are ways to get around this in Rust, but Rust is not really optimized for structured, manual memory management.
As a result I think there is plenty of room for something like C which just has better ergonomics and some more modern features.
When I see someone saying that they prefer D/Nim/Zig value proposition as a "better C" than Rust, what I see is that people are just starting to realize that there are many more options than C for doing programming tasks that require a more precise interaction with the hardware.
It's just not "assembly", but there are multiple different assemblers with different trade-offs. It's also not "assembler < C" anymore, since in some aspects newer languages do offer more low level control about certain things than C.
It's also not just C/C++/Zig/Rust/Nim/D competing at the lowest-level of the space. Ada, Forth, Scheme, and many other languages are also widely used in this space. They just aren't the "next new thing".
So only the old generation remembers how things used to be, and those that are curious about the computing history and evolution of programming languages.
That world is dominated by C++ for the most part, though. So D's -betterC would be fighting against an incumbent that is itself also already a "better C".
What value does D's -betterC bring to the table here? Skimming through it, it doesn't look like there's any compelling reason to switch to -betterC from an existing C++ code & knowledge base.
I think what a lot of people would want is something which maintains that simplicity, but mainly delivers on basic QOL lessons we've learned in the past 40 years, like that it's nice not to have to pass around array lengths as separate variables.
Which suggests an avenue I haven't seen anyone take yet: Pick a subset of features common to sane hardware and write a language which gives access to those features in a way which is reasonably portable and as explicit as C.
Pick a spot midway between a macro assembler and a language with a complicated optimizer and give as much access to the hardware as possible while not wedding yourself to a single ISA. Make cross-compilation a first-class feature using a module system, and error out if the programmer tries to use SIMD intrinsics when compiling for an MSP430 or something.
So, yeah, really not a C replacement at all imo
I would enjoy reading a couple paragraphs, or a blog entry about this.
So as long as UNIX clones exist C will be around. OSes with POSIX APIs is a different matter, because there the kernel can be something totally different, e.g. mainframes.
So for that, we still need something like Checked C.
Or as Oracle, ARM, Google are doing, hardware memory tagging.
It basically follows on the school of thought at Xerox PARC, ETHZ, and Microsoft Research.
Now what it lacks is more more manpower to improve its runtime capabilities and having a big name actually pushing it forward.
However this doesn't need to be a zero sum game, any language that helps to fix C is welcomed to the party, including attempts like Checked C and Frama-C.
Yes, betterC does not use the GC, but I was speaking about the whole language, and many anti-GC folks eventually discover that they can stick to regular D and still deliver what they were trying to do.
You can imagine an OS written in D, where BetterC mode gets used in the layers that for whatever reason cannot afford a GC, while all the remaning layers can happily take advantage of it.
https://www.twitch.tv/videos/602715503 [edit: at 10:20]
From the reference I found[1], Andrew's stance is: The current zig tooling forces spaces instead of tabs because the tooling for the language is not yet complete. The self hosted compiler (which the community will start using just as soon as it's ready) already does accept both tabs and spaces.
So, I'm not able to understand your complaint at all. Perhaps you could you elaborate, provide a reference, or soften your stance?
[1]: https://github.com/ziglang/zig/wiki/FAQ#why-does-zig-force-m...
- Want to access member in a aggregate (class/struct)? Use .
- Want to access member in pointer to an aggregate? Use .
- Want to access member in a module? Use .
- Want to access reference (not free standing)? Use .
This makes switching between different implementations pretty easy. Coupled with UFCS, this is pretty fantastic!
Just do a template
void zeros(T)(ref T arr) { arr.each!"a = 0"; }
someArr.zeros;
A often recurring C idiom is passing a pointer to a struct as function argument where passing the plain struct by copy would do. A big reason is the good old 'passing by pointer is faster', which I thought to be no longer relevant with modern optimizing compilers. Of course I found out the hard way that even on modern compilers object copies are not elided on call. I had performance sensitive parts of my (non-x86) code that were dominated by the compiler's builtin memcpy, due to my struct-happy coding style (e.g. rolling my own range struct and passing it by value everywhere).
I understand mostly why eliding argument copy is so much harder than eliding a return object copy, there are so many ways to observe its effect, and you have to obey the calling convention. Another aspect is the lack of programmer-communicated immutability in C, which you have addressed with D. Does the D compiler help in this situation? Can it guarantee that (immutable) argument copies will be elided in certain circumstances? (e.g. in file-scope static functions)
No, but it's an interesting idea I never thought of. By the way, passing by 'ref' works handily and avoids icky pointer passing, while being efficient. I recommend as a "best practices" coding style using 'ref' parameters instead of pointers where possible.
Not even with old compilers, necessarily, this is more about the CPU architecture. If you've got an architecture with no cache (eg 386 and below for Intel) you'll not care about cache miss vs cache hit, but once you have cache you'll often find that the pointer dereference will hit main memory, and thus be slower than just passing by value. Not always, of course, but sometimes, so since 1989 (for Intel) you've needed to profile that to be sure.
It was then up to the callee to make a copy if necessary, say if it modified the struct contents.
Hence it would have been possible to elide the copies, on a per function basis, depending upon how the function used the structure.
[1] ftp://ftp.linux-mips.org//pub/linux/mips/doc/NUBI/MD00438-2C-NUBIDESC-SPC-00.20.pdf
I was also thinking in the direction of the compiler transforming the call-by-value struct object argument into a call-by-ref one at specific call sites. e.g. when the object is clearly on the caller's stack, is not mutated by the function and the function is not taking its address.
As Walter pointed out, you can use refs in BetterC (and of course C++) directly, but I don't see why it cannot be automatically applied to C in general.
1. Why do functions need to be annotated with @safe and nothrow in betterC? Why not make them default? I understand making it default for non-betterC might break some code.
2. string type was uniform and awesome until it was treated as Unicode. Any plans to fix this and remove auto decoding? That would be awesome.
Edit: three questions to two. I had another question about using threads in betterC. But looks like we can't use D threads as they are runtime dependent.
2. I think you're referring to autodecode. There is an effort ongoing to extricate us from that, but it's difficult while maintaining backwards compatibility.
3. That's right. You'll have to use C threads.
See their Oral Histories collection: https://www.computerhistory.org/collections/oralhistories/
We've got a paper on the history of D accepted into this year's History Of Programming Languages (HOPL), which makes us very proud. Andrei, Mike and myself spent a lot of time combing through old emails and n.g. postings to develop an accurate timeline of when and how things came about and from whom.
I was really looking forward to the HOPL conference in London in June to present the paper, but CV scuttled that.
Is "Better C" Done? Or are there any features/changes being planned? Will it always stay backward compatible?
What is your vision for D/betterC/SafeD?
Is the intention at the moment to stay as a systems programming language only, or is your vision that D or betterC or SafeD gain traction as an embedded target language?
I definitely think the focus on correctness and the ease of unit testing would be great in the embedded development space.
What's the story in terms of using existing C (or C++) code with BetterC or D in general?
I'd pick up a comprehensive book like Ali Cehreli's "Programming in D",
https://www.amazon.com/Programming-Tutorial-Reference-Ali-Ce...
and come hang out in the D forums:
You can mix and match C and D code easily in the same program, and to a lesser extent C++ code. This means a larger project can be incrementally converted to D while keeping it running and shipping.
- what is the status of the ecosystem now?
- what are the big issues that make d less appealing?
- ms alexandrescu is still involved in the project?
- where do you see the language in 2 years for now?
I've used it myself to easily convert some of my older C programs to D and make them easier to maintain.
* Regarding the syntax of 'lazy'. It seems to me that it would make for better readability if the lazy keyword were required at the callsite, along the lines of doStuff(lazy getValueUsingExpensiveComputation()); rather than the current syntax where it's not clear at the callsite which, if any, of the arguments are lazy. C# does something similar with ref. What's the thinking behind D's syntax?
* What's the state, and future, of precise garbage collection in D?
Mainly that it be easy and quick for those familiar with C and C++ to get up to speed. With C, C++, and D, you cannot really know what will happen with the argument without looking at the corresponding parameter declaration.
It's a big boon that existing C projects can migrate one object file at a time to betterC, without needing to pull in extra dependencies. Moreover, embedded dev is where C is still the most entrenched due to its runtime simplicity (simple ctr0, linker script, and you're off).
Contract-based programming is a very nice way to quickly find errors and specify how different parts of the program should interact.
There are some Java annotation processors that rewrite the bytecode for contracts.
As extra info.
It's another layer of complexity, but it extends the language to offer a bit more richness or layers of abstraction.
I would not be surprised if a future C++ standard adds contracts officially. Boost seems to already have contracts: https://www.boost.org/doc/libs/1_67_0/libs/contract/doc/html...
Then again, I am biased.
printf("Hello %s", 123);
Then the D version will still happily compile without warnings and will segfault.Compiling with GCC -Wall -Werror, the type error is easily caught by the compiler.
A subset of C++ is a better C, that can be written in such a way that C compilers translate it, so that is meaningful. Well, at least a slightly better C, anyway.
2. set up to compile with dmc prog.c -c -betterC
3. replace all the preprocessor stuff
4. compile it, and fix the errors diagnosed by the compiler
The hardest part will be how much metaprogramming was done using the C preprocessor. Once that's dealt with, the rest is fairly mechanical.
https://github.com/DigitalMars/Compiler/tree/master/dm/src/d...
It still looks a lot like C.
For long-living and bigger code bases, worked on by teams, explicit types and "proper" static type system are the better choice.
E.g. it's less about readability, but maintainability.
Some excerpts "At one time, C was my go-to language for most programming. One day I realised that most of my C programs kept reimplementing things from C++: dynamic arrays, better strings, polymorphic classes, etc".
[1]https://theartofmachinery.com/2019/04/05/d_as_c_replacement....
Not that I'm suggesting this would be a better approach, but wouldn't it be possible to link both the C and D runtime libraries and wrap the main function to do the initialization?
All the features I like in D such as dynamic arrays and associate arrays are gone
- enumerate everything C is doing bad.
- presents fixes with a full bag of unnecessary features that no c programmer wants.
I wonder why there is no "Fixed C".
Fortunately, you can simply not use any feature you find unnecessary. We won't harangue you about it, I promise! (Well, maybe a little bit if it's so cool we just can't resist.)
So on Apple platforms they will eventually have to deal with C++ and Swift no matter what.
On Microsoft platforms, they complain about C support and get shown the door to C++.
And on Google platforms, given the years of ignoring security advices, starting with Android 11, hardware memory tagging is a required feature, with the kernel randomly attaching GWP-ASan to processes, while on ChromeOS Linux gets to run on a hypervisor sandbox.
What I got: some 50,000 foot pure functional typeless language with loads of magic in the compiler that you'll never be able to reason about without having written one yourself.
That's the problem. This isn't a technology issue, it's a social one.
examples in top of my head:
- adding object oriented feature like built-in constructor/destructor while only default values are needed as week as a defer statement.
- weird template, while I can sense that we only want a proper hygienic macro system.
And "array type", pointer with length, to deal with contiguous memory.
The rest is well described in the video, but those 3 points are my major issues.
Also array type is the single biggest thing required to fix C. How many bugs in big C projects are caused by bad indexing and overruns.
On top of, "oh no free features".
The remaining C usage is a mix of existing domain expertise, existing large codebases impractical to migrate to anything else (eg, Linux), or a rejection of anything more than what C provides.
In all of those cases anything that's not exactly C is unlikely to motivate any changes. The users that could change to a "Fixed C" already did decades ago.
I can understand that "you don't have to use any features if you don't want to" is somewhat silly when talking about C++, since it has so many features that can bite you when you least expect it, especially when dealing with years of legacy code. D is far better designed than C++, however; it would not take you nearly as long to learn enough D to be comfortable reading others' code.
All I'm trying to say is that "C, but without the problems" might actually look more like BetterC than you think it does. True zero-cost abstractions are clearly still an unsolved problem, but abstractions are a necessity. C's niche is rapidly disappearing.
Also, out of curiosity, what don't you like about Zig? I saw this on your website, but I couldn't find any specific issues you'd had with it.
> Wow, Zig is competitive with assembly?
> Yeah, I totally had the same reaction. I’m interested to see how it measures up under more typical workloads. People keep asking me what I think about Zig in general, and I think it has potential, but I also have a lot of complaints. It’s not likely to replace C for me, but it might have a place somewhere in my stack.
It's just the CS community, at some point when you are writing languages you tend to try to outsmart the language you are fixing by creating overly complex behavior. Over-engineering is every single new languages.
Even Zig fails to do better than C, I think it's syntactically a disaster.
Here is a few lines from the documentation:
const ptr = @intToPtr(?*i32, 0x0);
while (it.next()) |item| { /* ... */ }
pub fn main() anyerror!void { /* ... */ }
exe.addCSourceFile("test.c", [_][]const u8{"-std=c99"});
const file = std.fs.cwd().openFile("does_not_exist/foo.txt", .{}) catch |err| label: { /* ... */ }Here's what I see in your example:
- @ indicates built-in function, which avoids namespace collisions.
- Optional types via the ?, which solves the null pointer problem.
- Real iterators, which are less error-prone and nicer to read than traditional for loops in a lot of common applications.
- The || syntax is better than something like `for (type var : array)` in Java, don't you think? Especially since it works with any iterator?
- anyerror!void is a nice way of saying that the function can return an error. Remember that we don't have exceptions here.
- It has interoperability with (multiple standards of) C.
- Error handling is higher-level and less error-prone than in C without exceptions that can create hidden jumps in your code.
So it clearly solves issues that people run into frequently in C. It brings in a nice sampling of high-level language features without doing anything that would compromise its niche as a systems language. It still has manual memory management and does not have exceptions. The behavior is simpler and requires that you language-lawyer the specification for undefined behavior far less often than in C. Your knowledge of C isn't necessarily enough to be able to immediately read Zig code, but that's because Zig isn't C. It's not hard to learn.