Confused by comment in Rust By Example's TempFile example

⚓ rust    📅 2025-04-25    👤 surdeus    👁️ 1      

surdeus

I'm working through Rust By Example and am currently looking at 16.4 (Traits > Drop). In it there is an example that implements a simple TempFile. However, the comment about the Drop implementation surprised me. The comment reads:

// When TempFile is dropped:
// 1. First, the File will be automatically closed (Drop for File)
// 2. Then our drop implementation will remove the file

My interpretation of this is that when TempFile is dropped, first its field file: File will be dropped. When that happens, file.drop will run and will close the file. Only then will TempFile::drop run.

I thought that TempFile's fields would remain un-dropped until TempFile::drop finished so that it would have access to them. So my belief is that the two steps would happen in the opposite order the comment seems to be describing.

Is the comment correct and I somehow got an erroneous belief about how destruction works? Am I misinterpreting the comment? Is the comment potentially wrong?

4 posts - 4 participants

Read full topic

🏷️ rust_feed