Get the latest tech news
Cursed Linear Types in Rust
Inspired by Jack Wrenn’s post on Undroppable Types in Rust, I set out to see if it’s possible to create types that must be used exactly once. From my understanding, those things are called linear types, but don’t quote me on that1. Unless you are quoting the title of this article which explicitly says linear types… I feel stupid now. ↩
To my understanding, it relies on the fact that the compiler can reason that the drop implementation does not have to be generated when consume is called due to ①. There’s some additional unsafe trickery in ②, which is not terribly important but it’s actually safe. Thirdly, as was pointed out by u/SkiFire13 in the original reddit thread, this trick relies on the compiler’s ability to reason without optimizations that the type will not be dropped. Thus, simply sticking a function call between the creation and consumption of the instance will make this code fail:
Or read this on Hacker News