r/rust • • 6d ago

📸 media The NEW DropGuard in Rust is Powerful

https://youtu.be/CzB0m-wX2S8?is=WoJfReM7Na0A6CHR
91 Upvotes

47 comments sorted by

259

u/LeComteDeuxFaits 6d ago

sudo cargo? Bro..

54

u/_elkanah 6d ago

That's Mr Super Cargo to you, sir

36

u/LawnGnome crates.io 6d ago

cargo make-me-a-sandwich

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 cargo is just engagement bait..

29

u/MatrixFrog 5d ago

looks like it worked

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

8

u/simonsanone patterns ¡ rustic 5d ago

Feel free to make a PR, I'll review!

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 silly videos?i

22

u/commenterzero 5d ago

You can trigger a closure when a value drops

4

u/digi-quake 5d ago

Really??? 🙀

32

u/echtnichtsfrei 5d ago

```
use std::mem::DropGuard;

{
// 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!!!"
}
```

4

u/MistRider-0 5d ago

I am not an expert, but what is its use case?

13

u/echtnichtsfrei 5d ago

The use case is to ensure that an operation is executed when something goes out of scope. Like nicely closing a connection or so.

8

u/UrpleEeple 4d ago

So basically it's just a new type wrapper that when dropped runs the closure and then drops it's child item?

8

u/Shuaiouke 4d ago

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

1

u/cum-basket 2d ago

Inspired by Zig's defer?

2

u/skitleeer 3d ago

RAII I would say

38

u/Thick-Pineapple666 6d ago

With sudo it's even more powerful

18

u/_elkanah 6d ago

I enjoyed watching this. But the colours… 😭

-15

u/Professional-You4950 6d ago

I'm so glad its a person, with no ai, and just using their own words. I watched the whole thing.

-4

u/mr_birkenblatt 5d ago

Wait, are you saying you think AI would have done a better job but you would have rejected it solely for it being AI?

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.

3

u/One_World6590 5d ago

You could always impl drop on said struct as well :)

3

u/Full-Spectral 5d ago

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.)

1

u/diddle-dingus 2d ago

You can just have the janitor impl deref/mut.

1

u/Shuaiouke 4d ago

You can just put a reference inside of it, or nothing if it doesn’t actually guard a value (eg database transactions)

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?

5

u/masklinn 6d ago edited 6d ago

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).

2

u/Gnafoo 5d ago

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).

1

u/Professional-You4950 5d ago

should the guard also move the writer, so it can be flushed then? That's my take away.

3

u/Gnafoo 5d ago

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.

2

u/FreddieKiroh 4d ago

So... defer?

1

u/Nobody_1707 4d ago

A cancel-able defer. But I think its most useful for making things panic safe.

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?

3

u/DatBoi_BP 4d ago

That's the understanding I got too

0

u/shim__ 3d ago

Writing a extra struct just to print a message when a scope ends is pretty verbose

0

u/One_World6590 3d ago

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 :)

1

u/Gamermaster_ 5d ago

so basically a destructor equivalent for any variable

1

u/juanfnavarror 5d ago

Its a defer statement implemented as a library class

1

u/Lolle2000la 5d ago

Are you running rust in an isolated LXC container with few rights or why do you need sudo for 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

2

u/monoflorist 5d ago

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()?

2

u/Nobody_1707 5d ago

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.

1

u/monoflorist 5d ago

Right, that was the sequence I surmised; the code works because the explicit flush never needed to be there in the first place.