Rust for C++ programmers – Part 8: destructuring
featherweightmusings.blogspot.com
featherweightmusings.blogspot.com
Just a gentle suggestion, have you considered putting some syntax highlighting on the code portions of your site so that it is more readable? I find it a little hard with the grey on grey scheme even though the Rust itself is super elegant.
The repo, from which the book is built, is available on GitHub: https://github.com/aminb/rust-for-c
I tried contacting and asking him before, but didn't hear back, so I just went ahead and did it myself.
match x { (y) => { ... }
and: match x { (ref mut y) => { ... }
In there too. I think ref x matches (particularly from Result) are pretty common.It's not that structs with Drop can't be destructured, but that they can't be destructured and moved. For why that's a bad idea, consider this example (from the original bug implementing this behavior, https://github.com/rust-lang/rust/issues/3147):
let {f, g, h, _} = move foo
(The `move` keyword is no longer in Rust, but local variables with a type implementing Drop are implicitly moved, not shallow-copied, when used as an rvalue, since it is only safe to run a destructor once on the same structure).The problem is that there's no obvious place to run the destructor. Destruction for items with the Drop trait in Rust proceeds as follows: first the value's destructor is run, then the value is completely destroyed, and then the values of any of its children are run. Clearly, then, the destructor must be run after the let, or the item's fields would be uninitialized at destruction time--but there's no longer any available reference to the item upon which Drop can be run.
There's at least one proposal to fix this floating out there (https://github.com/rust-lang/rust/issues/11855). The basic idea is to alter destruction semantics so that the three steps of destruction can be split up. This would allow Rust to run the destructor for the original item, then move any referenced fields out of the item, then destroy the item, and then run the field-level destructors for any items going out of scope.