Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Rust's zip has a specialisation for iterators with a trusted length. Such as slice iterators.

`zip` yields exactly the same assembly as a loop over the index range with an unsafe item access: https://godbolt.org/z/7ebfxbhxc



For Zip it's TrustedRandomAccess[0] instead of TrustedLen. Imo the most radioactively unsafe trait in the standard library and will likely never be stabilized in its current form.

[0] https://github.com/rust-lang/rust/blob/f540a25745e03cfe9eac7...


That's cool. At the same time though, it almost feels like a distinction without a difference in some ways - Zig has a special built-in syntax; Rust doesn't use special syntax, but it does use complex special-cased unsafe code in the stdlib in order to implement a safe + performant API.


Rust's is built on top of (and exposed to) Iterators, which are a very general concept that can be rooted in all kinds of data structures, composed in all kinds of ways, and collected/processed in all kinds of ways (i.e. the user's code might not even contain an actual loop). The code continues to work in many situations, even where the optimization doesn't apply

You trade some special-case syntax and ergonomics for that generality, but it is very general even if not all of it is optimized in the same way


On the other hand, the "special cased unsafe code" is applicable to more than just zip, more than just the one array type, and is available in userland (though currently unstable so nightly only, both to implement it on a bespoke type and to rely on it).


You have to pass -O though, the point of Zig's for loop syntax is to get fast compile times and good performance also in debug mode :^)


Interesting, are "trusted-length" iterators something that might ever make it into userspace? Maybe as const generics?


It’s already in userspace, though nightly (and unsafe, obviously), so whether it’ll be stabilised, and in what form, is an open question: https://doc.rust-lang.org/std/iter/trait.TrustedLen.html




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: