by blackrock · 8y ago · 0 comments
=======================
fn transmute_lifetime<'a, 'b, T>(t: &'a (T,)) -> &'b T {
match (&t, ()) {
((t,), ()) => t,
}
}=======================
I thought Obfuscated-C was hard to read. Then C++ with all its templates. Now, I'm thinking Rust has taken the prize.
Here's a similarly horrible Java example, from a recent HN post on Java's type system being unsound: https://twitter.com/joshbloch/status/822948565433466881
It's more verbose, because Java, but equally dense relative to the language as a whole.
This is not supposed to be good code.
- Every reference has a different explicit lifetime—one input, one output—which would rarely ever show up in real code.
- There is a tuple with 1 element, which I have never seen in the wild.
- It's matching against `()`, the void type, which is never done because it's useless.
A function 'transmute_lifetime' that takes a tuple of generic type T with lifetime 'a and returns a T with lifetime 'b...
And then the code itself, beyond the function signature, is trivial destructuring matching.
If you're not familiar with the syntax of a language, of course it won't be easy to read.
perl and bash can rapidly devolve into symbol salad if you don't know them. If you don't know es6, javascript's spread and destructuring assignment syntax can look every bit as strange.
That all being said, the point of this rust code was to be a minimal example. Minimal reproducers are often nonsensical and unidiomatic, which helps put this in further context.
I think the original un-minimized crashing code was this: https://github.com/rust-lang/rust/issues/52213#issuecomment-...
That's clearly more readable, and that's what more typical rust looks like.
It's being presented as a terse explanation of what the bug was and how it was triggered.
I didn't spend an hour or two understanding that code, I spent less than a minute because I already know rust.
I don't understand your point. The code served its purpose well: for the audience (rust users) it demonstrated the bug (lifetime unsafety in match ergonomics change).
If the audience were "people who don't know rust", then of course that code wouldn't be a good demonstration, but that's not who the audience for this post is.
I don’t really know Rust all that well beyond a few toy projects. But if you were familiar with core aspects of the syntax and semantics - lifetimes, generics, tuples and the void type in this case - then it’s not particularly complex. Add to the fact that it’s code you’re not actually going to see in practice and I don’t think it’s so bad!
Also, there's nothing obfuscated here, and everything is explicit if you know the syntax.
The alternative is not caring and leaving everything for a GC and/or validating values with runtime checks instead. There are other languages which chose these approaches.