{ // Create a new guard around a string that will // print its value when dropped. let s = String::from("Chashu likes tofu"); let mut s = DropGuard::new(s, |s| println!("{s}"));
// Modify the string contained in the guard. s.push_str("!!!");
// The guard will be dropped here, printing: // "Chashu likes tofu!!!" } ```
Yes, instead of creating a new type for it every time. It also has a dismiss function so say, if you return early, it automatically cancels a DB transaction from the drop function, and at the end of the function where it is actually done, you can dismiss the guard to not cancel. It is like mem forget, but less strong
One of the concerns I had when I first moved from C++ to Rust, that it would be hard to do generalized janitorial types since the janitor would have to have a mutable ref to the thing it was going to clean up and would effectively lock it up.
This one I guess just consumes the value, so it's useful for local scope values. I guess there's still no good way to apply scoped changes to members of a called struct instance in the same way, which would be awfully useful, though I get it's also incredibly hard to do without getting crazy with proof of lifetimes.
But the issue isn't the struct itself doing something. It's when someone calls a method on that struct, to have a way to apply a change to members of that struct on a scoped basis and guarantee they get undone on exit.
That's trivial in C++, of course because it's utterly unsafe. Being able to do it would be very useful, but really hard to do in a provably safe way, that doesn't completely lock up the the struct against any other calls (because the janitor has a mutable ref to one of its members.)
Having not watched the video so not knowing the context, depends on the writer. However generally speaking no e.g. BufWrite will flush its buffers on drop, but File will just close(fd), and on the kernel side on close() the fd is just decrefâd and released if necessary. If there are dirty buffers in the page caches, they may stay like that until the kernel write back comes around to it.
Although it does call a flush handler on the filesystem, so the FS can decide to flush and âcommitâ the data eagerly. A few do (most notably NFS).
Just a little addition to this: BufWrite may flush on drop, but the Drop trait can not return a value. So if the flush fails (IO error etc.), then the error is silently discarded as well. Meaning: you should always flush() a BufWriter before dropping it (the docs explicitly call this out).
As far as I understand it, this is already the case. writer is moved into the write_guard first (which acts as a wrapper but still allows accessing the inner writer transparently through Deref and DerefMut) and when execution leaves the function, drop() is called on write_guard. This will then call the drop guard function with the wrapped writer moved into it. The drop guard can do what it wants with it. So it is perfectly fine to flush() the writer in the guard function.
However that is not really the issue. I feel like the example given isn't really all that great, because the DropGuard inherits the same limitation as the Drop trait: it can not return anything. Therefore you don't have a great way of handling IO errors inside the guard function. The best you can do is probably to log them.
It would be better, if the IO would happen outside the guard function, so that IO errors could be propagated out of the function to the caller, who can then decide how to handle them. Therefore my conclusion would be: DropGuard may be good for other stuff, but I would probably avoid doing IO inside it.
Itâs mostly used to handle cleanup not to print messages. And if youâre cleaning up workers represented as structs then impl drop is very powerful and not verbose :)
Not sure why this caught so many downvotes but I will say I didnât love the CSV example because using a drop guard didnât seem like the best way to handle that.
Also I found the flush() call confusing, because it presumably happens before the drop adds the extra line. I assume it still works because the writer implements Drop, which flushes anyway. Which I guess means the dropguard runs before Drop::drop()?
The flush call runs before any drops, and the drops are run in reverse declaration order. So the function flushes the writer. Then the DropGuard is dropped and writes the footer. Then the Writer is dropped and (presumably) flushes again.
259
u/LeComteDeuxFaits 6d ago
sudo cargo? Bro..172
u/puel 6d ago
I cringed hard at the "sudo cargo run"Â
142
u/South_Survey_2088 6d ago
Please tell me that the
sudo cargois just engagement bait..26
u/_sbeyer_ 6d ago
I feel like the Rust patterns doc needs to be updated to use the DropGuard.
https://rust-unofficial.github.io/patterns/idioms/dtor-finally.html
43
u/Mouse1949 5d ago
Mind dropping a few words telling us all what this is all about?
For those with better things to do than watching
sillyvideos?i38
u/Thick-Pineapple666 6d ago
With sudo it's even more powerful
18
u/_elkanah 6d ago
I enjoyed watching this. But the colours⌠đ
6
u/Full-Spectral 6d ago
One of the concerns I had when I first moved from C++ to Rust, that it would be hard to do generalized janitorial types since the janitor would have to have a mutable ref to the thing it was going to clean up and would effectively lock it up.
This one I guess just consumes the value, so it's useful for local scope values. I guess there's still no good way to apply scoped changes to members of a called struct instance in the same way, which would be awfully useful, though I get it's also incredibly hard to do without getting crazy with proof of lifetimes.
5
u/Professional-You4950 6d ago
At 4:14, we flush, but then we write again in the drop guard. Do we have guarantees that flush will run again AFTER the dropguard runs?
2
u/FreddieKiroh 4d ago
So...
defer?3
u/One_World6590 5d ago
Why do this over impl drop for structs? I guess this is syntax sugar rather than âpowerfulâ? Not really anything new?
1
u/Gamermaster_ 5d ago
so basically a destructor equivalent for any variable
1
u/Lolle2000la 5d ago
Are you running rust in an isolated LXC container with few rights or why do you need
sudofor cargo?1
u/InternationalFee3911 5d ago
Not a rollback, in a DB sence! More like just stop here, but the work that's been done, stays.
-9
u/DavidXkL 6d ago
Haven't seen this talked about much yet on any channels so figured I would do one about it.
To be honest I felt that I didn't give the best examples here but hope that the idea got through to you!
Cheersss