8 ms·
When Zig Is Safer and Faster Than Rust
- crvdgc 2y agoMaybe the title needs to be edited to "unsafe Rust".
- Symmetry 2y ago> The garbage collection is the important part, it’s hard to make it work and be fast and be safe because its fundamentally a problem that doesn’t play nicely with the borrow checker. That's fair, use the right tool for the right problem. For most applications you can just use a garbage collected language after all.
- erlend_sh 2y agoFor a pure Rust answer to “how to make a primarily-safe gc-lang in Rust”, see Piccolo (Lua) with its ‘Stackless VM’: https://github.com/kyren/piccolo https://github.com/kyren/piccolo That’s not to say Piccolo couldn’t theoretically benefit from having its (already isolated) unsafe parts rewritten in Zig, but that’s up to the Zig developer community to chip away at with upstream contributions.
- Sytten 2y agoApart from syntax sugar over which I agree should be improved, the argument sells to boil down to: my language doesn't enforce a borrow checker so it is UB safe. Which in my book is just not true. The allocator example the user gives is not really good since if he had another try in between the alloc/free I assume the memory would not be freed, Drop semantic is better in that regard. You can also set a global alloc that check for missing free in rust though probably not as nice as a localized one.
- hansvm 2y ago> try between the alloc/free The idiomatic way to handle that is with some combination of `defer` and `errdefer`. Then, in code, there are no lines between alloc/free, and if a try would exit before the free then you would instead first free anyway. > drop semantic is better in that regard The drop trait has its warts too. Zig's version sets up a point in time where the given cleanup code _will_ run (ignoring power outages and the like), and Rust's sets up a point in time where the given cleanup code is _allowed_ to run. It solves UAF, but it makes performance harder to reason about and makes leaks easier to write (a common theme in my complaints about Rust -- it's mostly a nice language, but many of the design choices slightly encourage leaky code, so most projects of any size and complexity have leaks). Having drops be that easy to write also encourages programmers to think in terms of small units of data rather than collections and common lifetimes, typically resulting in increased execution times.
- Sytten 2y agoYou literally don't leak memory in safe rust, that is kinda of the whole point. If you use smart pointers sure you can leak but that is not only rust, any ref counted abstraction has that. Drop IMO is preferred over defer because you can't forget to call a free. If you encapsulate your unsafe (which you should), you can guarantee it will be freed. I much prefer that. If you want to free early just call drop manually, after that if the memory is not freed then that on you to set an allocator basedon your needs.
- estebank 2y agoI like Drop. Memory leaks in Rust are incredibly uncommon. But they are considered memory safe. Box::leak is declared safe, as per the leakpocalipse right before 1.0. A memory leak that is still pointed at by a dangling pointer is not going to cause UB, even though it is still a bug.
- hansvm 2y ago> You literally don't leak memory in safe rust, that is kinda of the whole point. That's a common misconception. Safe Rust prevents use-after-free, double-free, accessing uninitialized memory, (an extremely constrained form of) data races, and a number of other things. It doesn't give a rip about leaks beyond a best effort. Leaks do not violate memory safety. Part of the reason it doesn't care is because it's hard to infer your intent. A common class of bug is accidentally boxing a reference to something you'd like to drop (this and similar flaws afflicted Actix till at least the 3.0 release). Rust confirms you don't have UAF and that you don't drop the data before you're done with it, but by accidentally writing it so that it lives nearly forever that drop is never executed. Rust, similarly, makes no guarantees about drop's behavior at any point in time (other than that it won't be executed to soon and should usually attempt to be executed eventually), but definitely not near program shutdown or similar. It's especially dangerous because a huge fraction of programs run correctly regardless most of the time.
- nurettin 2y ago> You literally don't leak memory in safe rust, that is kinda of the whole point. Memory leak is not the same as dangling reference. A loop pushing too many values into a vector can be considered as a memory leak.
- nextaccountic 2y ago> Rust’s raw pointer types are nullable by default and have no null-pointer dereference checking. There is a NonNull<T> pointer type that gives you more safety. I’m not sure why it’s not the default, since Rust’s references are non-nullable. NonNull<T> would probably be a better default indeed, but one reason might be that NonNull<T> has more UB than *mut T (namely, it is UB for it to be the null pointer). (A lot of the text is about how more UB makes unsafe programming harder, which is a fair point) > Zig pointers, by default, are non-null and you opt-in to nullability using the ? syntax (e.g. ?*Value). And of course, you get null pointer dereference checking enabled by default too. Well so Zig pointers, by default, has more UB than Rust pointers, at least when concerning null pointers.
- throwawaymaths 2y agothere is no UB in zig pointers in ReleaseSafe compilation mode.
- hansvm 2y ago> Well so Zig pointers, by default, has more UB than Rust pointers, at least when concerning null pointers. Not quite. In Zig, a (non-C) pointer type is closer to a Rust reference in its behavior. It isn't null, and that's enforced by the type system. The author's point about opting into nullability is that in a function signature you can choose to allow null pointers to be passed to the function by making the argument type an optional pointer, a weaker type with the same safety guarantees (because, like with Rust, the type system forces you to handle the null branch).
- jackschultz 2y agoIn the tl;dr at the start >So is Zig a better alternative to writing unsafe Rust? The title here and what he has in his post are the same, but in the tl;dr along with the slug of the url which is "unsafe-rust-vs-zig". We need to realize it's a very specific case he's talking about, rather than in general. The pain of titles.
- mrcsd 2y ago> Writing a substantial amount of unsafe Rust really sucks the beauty out of the language. I really disagree with this take, given the examples of unsafe code the article chose to exhibit. Trying to write C in Rust totally goes against the grain of Rust's ergonomics, which are oriented towards discouraging unsafe code patterns. It should be a pain to attempt something dangerous, and it should feel really easy to write safe code, because this setup naturally encourages the vast majority of code to be written safely.
- gr4vityWall 2y agoIt sounds to me like you agree with the author. They used similar wording to you by the end of their post: > It was a major pain dealing with all the nuances of unsafe Rust.
- ajross 2y agoThis sounds like just prescriptive orthodoxy. In fact lots of applications, including big chunks of Rust's own standard library, need unsafe to correctly express their algorithms (doubly linked lists and balanced trees are famous examples of things that can't be borrow checked, the use case in question appears to be a collected heap which would likewise need to live in the same space). Deciding that these areas "should be a pain" seems tantamount to saying Rust shouldn't be used for them. Which is sort of the article's point.
- do_not_redeem 2y agoRust's approach is more like a "keep off the grass sign" than a barbed wire fence. If Rust really wasn't meant to be used for these things, it wouldn't have the unsafe keyword at all. But instead of forbidding those things entirely, it just makes them uncomfortable. This nudges the programmer to question if they really need to be on the grass to accomplish their goal, and helps subconsciously steer them onto the safer path. This is the "strategic use of friction" described here, ironically enough, by the creator of Zig: https://github.com/ziglang/zig/issues/3320#issuecomment-884478906 https://github.com/ziglang/zig/issues/3320#issuecomment-8844...
- pjmlp 2y agoThe solution for "fixing" use after free was already a thing 25 years ago in C and C++ code, hence why it is hardly an improvement in Zig. https://learn.microsoft.com/en-us/cpp/c-runtime-library/crt-debug-heap-details?view=msvc-170 https://learn.microsoft.com/en-us/cpp/c-runtime-library/crt-... https://www.parasoft.com/products/parasoft-insure/ https://www.parasoft.com/products/parasoft-insure/
- anon-3988 2y agoI feel like there's space for imperative, garbage collected, pattern matching, and ADT language. Just Golang + pattern matching + ADT. I would be sooooooooooooooooooooooooo happy. I think there ought to be a subset of Rust that uses Arc for everything, maybe with a language feature that desugars into it. Obviously this requires compilers to be able to reason and optimize out atomics.
- ThePhysicist 2y agoI think we might get these eventually in Golang, at least to a degree. In the end it's just a question whether they will be zero-cost like in Rust or incur some runtime overhead (I would assume the latter). Would be fine for me, I rely a lot on reflection for more complex use cases around dynamic typing and that already has a significant runtime cost (which is still ok in most cases).
- russell_h 2y agoI wouldn’t use this in production, but this was in HN earlier this year and I love the idea: https://github.com/borgo-lang/borgo https://github.com/borgo-lang/borgo
- zokier 2y agoOcaml, F#, Reason, ReScript, Scala? Or any other of the million ML style languages?
- anon-3988 2y agoI tried OCAML, My problem with it is that it smuggles in a lot of other concepts too. Especially with the thing about bindings and mutability. Also, the syntax. Every FP languages tends to be "pure" and remove every "unnecessary" syntax to achieve some kind of "simplicity". No, I want a true cavemen language. Treat me like I'm a low IQ idiot. "This function returns Option<T> DURRR ME HAVE TO MATCH ALL. ME DON UNDERSTAND WHAT "_" CLAUSE IS. ME NO UNDERSTAND LIFETIMES, LAST TIME I WROTE THE C BINDING ME BRAIN ALL FRY". There's a space for language for people who: 1. learn the language in 1 hour 2. spend 100 hour writing the most mundane, verbose code instead of: 1. learn the language in 100 hour 2. spend 1 hour writing the most beautiful, concise and pure code
- ksec 2y ago(2023) Last submission and discussions with 221 comments. https://news.ycombinator.com/item?id=35058176 https://news.ycombinator.com/item?id=35058176
- pie_flavor 2y agoThe premise of the Rust half of the article makes no sense. 'Rust has more rules' is not true, references have more rules, and in unsafe code, you aren't using them very much. Comparing the rules that apply to references in Rust to the rules that apply to raw pointers in C and Zig is nonsensical: if you transliterate the Zig code to Rust, no new problems appear! 'What if I create a reference' is easily solved by not creating a reference, just as you are not creating a reference in the Zig code (because Zig doesn't have them). Every problem on Rust's end was just trying to use references instead of pointers. The article then trumpets Zig's tracing allocator as a unique benefit, even though you can do the exact same thing in Rust.
- 3836293648 2y ago> What if I create a referecnce is easily solved by not creating a reference Except it isn't easy. Rust implicitly creates references constantly and in unsafe code it may be UB for those to exist. It's why Rust has all the crazy offsetof macros and such because you can't reliably do the obvious &raw (*struct_pointer).field
- SkiFire13 2y agoI guess you meant the `addr_of!`/`addr_of_mu!` macros? Those have since been given proper syntax with `&raw` and `&raw mut` expressions.
- NobodyNada 2y ago> &raw (*struct_pointer).field This is not correct -- dereferencing a raw pointer does not implicitly create a reference. That code snippet is perfectly valid as long as the underlying pointer arithmetic is valid. See the Rust reference on "Behaviors considered undefined": [0] > Accessing (loading from or storing to) a place that is dangling or based on a misaligned pointer. No problem here, dereferencing a raw pointer creates a place expression but we do not load or store from it. > Performing a place projection that violates the requirements of in-bounds pointer arithmetic [1]. A place projection is a field expression, a tuple index expression, or an array/slice index expression. Alright, so we're doing place projection. Let's check the link to see the requirements for in-bounds pointer arithmetic: > The offset in bytes, computed on mathematical integers (without “wrapping around”), must fit in an isize. > If the computed offset is non-zero, then [the base pointer] must be derived from a pointer to some allocated object, and the entire memory range between [the base pointer] and the result must be in bounds of that allocated object. In particular, this range must not “wrap around” the edge of the address space. Okay, so your "obvious" snippet is sound as long as struct_pointer points to valid memory that's at least big enough to contain the field offset you're accessing. There's no rules about aliasing, or even alignment. These semantics are more or less the same as the equivalent C code. They might even be slightly more relaxed, since I don't recall if C has requirements on alignment or strict aliasing when doing pointer projections. I have no idea what Zig's requirements are -- I spent about a half hour searching and couldn't find any documentation or discussion on whether and when pointer projection, or even just pointer arithmetic, can lead to undefined behavior in Zig. I'd be pretty uncomfortable writing pointer heavy code in Zig when I can't find documentation or even a GitHub issue on whether basic pointer operations can trigger UB or not. [0]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html https://doc.rust-lang.org/reference/behavior-considered-unde... [1]: https://doc.rust-lang.org/std/primitive.pointer.html#method.offset https://doc.rust-lang.org/std/primitive.pointer.html#method....
- bfrog 2y agoDoes zig now enforce memory ownership rules and signal all things have well defined behaviors? No? Ok then its not safer. Title is misleading at best and downright false at worse.
- VeejayRampay 2y agoone day we'll see an article about zig not trying to piggyback on rust's success
- ameixaseca 2y agoA few notes: 1) Lack of a garbage collector does not make your program faster, it makes the performance more easily predictable in terms of latency. It also makes it more friendly for memory bandwidth, CPU cache and to overall memory usage, which in turn results in better performance in real-case scenarios vs synthetic/toy benchmarks. This is particularly noticeable in constrained environments (like embedded systems). 2) Zig was never about memory safety, and it is not a memory-safe language. It might have better plumbing than C, it might add better way to implement and abstract concepts.. but so does C++, for instance. The more striking differences between C++ and Zig, IMHO, are syntax and the ability to use the same language instead of a separate one to do meta-programming (templates vs comptime). 3) Aliasing enforcement in Rust is there for a reason. Two examples I quickly found on Zig's issue tracker: * https://github.com/ziglang/zig/issues/3696 https://github.com/ziglang/zig/issues/3696 * https://github.com/ziglang/zig/issues/5973 https://github.com/ziglang/zig/issues/5973
- pod_krad 2y ago>1) Lack of a garbage collector does not make your program faster, it makes the performance more easily predictable in terms of latency. AFAIK, some time ago non-predicable GC behavior was the reason why Discord migrated from Golang to Rust. Also predictable latency is important for real-time applications.
- deleted 2y ago[deleted]
- fithisux 2y agoIt is still in Rust.
- dgares 2y agoNo, there's parts of Roc that are in Zig[1]. At a glance, it seems like they moved mostly-wholesale over to Zig at one point, then moved back while still keeping some parts. [1]: https://www.roc-lang.org/faq.html#rust-and-zig https://www.roc-lang.org/faq.html#rust-and-zig
- hitekker 2y agoYou may have glanced too quickly. The article says: > Roc's compiler has always been written in Rust. Roc's standard library was briefly written in Rust, but was soon rewritten in Zig.
- LAC-Tech 2y agoZig has a singular focus on doing low level systems programming and it shows. Rust is very nice for systems programming, but it's not as ergonomic as Zig at all. Of course, it's a much nicer and more comfortable general purpose language. I think both languages are great and hope to see them used more and more in the future. It's much better to debate when to use Zig and when to use Rust then go back to the dark days of C and C++.
- jasfi 2y agoThen there's Nim which is great as a general purpose language and has great ergonomics too.
- drannex 2y agoBut, ran by a BDFL that doesn't ever want to become a foundation and share power, is known to throw tempter tantrums, and freaks about LGBTQ people and creators.
- planetis 2y agoI would ask for a source for your claim but we both know it's bull.
- drannex 2y agoI wrote this on Mastodon, but I will copy it over here. Because he spouts nonsense all across the forum on a fairly regular basis. The creator is a BDFL but they are against setting up a foundation because they <i>"lost faith in mankind"</i> and then ranted about "master vs main" on git, and used that to segue into a mini-rant on essentially "woke" ideology. In less than 500 characters. > Here is a hint: If you are obsessed with racism and sexism it's because you're a racist and sexist. Now go and cancel "He-Man - Masters of the Universe" because obviously He-Man is a slave owner. I get the vibe they might be racist, sexist, and just a bit out-of-touch with reality. I wouldn't trust having corporate code, or any code, built on it. Dude is a bit unhinged in that regard. ["Nim Forum: Nim Succession Plan, 2023"](https://forum.nim-lang.org/t/10312 https://forum.nim-lang.org/t/10312)