破棄と__del__
値のライフタイム終了時に後処理を行います
「破棄と__del__」はCoddyKit上の無料Mojo Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMojo Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Mojo Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Every Value Has an End
When a value is no longer needed, its life ends and Mojo destroys it. This is your chance to clean up what it owned. 🧹
The Destructor Method
Mojo calls a special method named __del__ to destroy a value. It runs automatically when the value goes out of scope.
fn __del__(owned self):
passDeterministic Timing
Mojo destroys values at a predictable point, as soon as they are last used. There is no waiting on a garbage collector.
Last Use, Not Block End
Mojo runs __del__ right after a value is last used, often before the block closes. This frees resources as early as possible.
Free What You Own
If your type holds a heap buffer, __del__ is where you release it. Doing so prevents memory from leaking over time.
You Own the Cleanup
Inside __del__ the value is owned, so you can safely tear down its resources. After this, the value no longer exists.
Often Synthesized
For simple types you write nothing. Mojo synthesizes a destructor that cleans up each field in turn, so leaks are avoided.
When to Customize It
Write your own __del__ when you manage a raw resource, like an allocation or file handle, that needs explicit release.
Runs Once, Exactly
Each value is destroyed exactly once. Moves transfer ownership so only the final holder runs __del__, avoiding double frees.
No Use After Death
Once __del__ completes, Mojo guarantees the value is gone. Its ownership rules stop you from touching freed data.
Safety Without a GC
Deterministic destruction gives you C-like control with built-in safety. Cleanup is timely, predictable, and automatic.
Quick Check
Lets check destruction.
Recap
__del__ runs when a value’s life ends, deterministically and exactly once, letting you clean up safely without a GC. 🎯
よくある質問
「破棄と__del__」レッスンは無料ですか?
はい。「破棄と__del__」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Mojo Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Mojo Academyコースには全4レッスンが含まれています。
「破棄と__del__」で何を学びますか?
値のライフタイム終了時に後処理を行います ブラウザで直接実行するハンズオンコードでMojo Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Mojo Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMojo Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「破棄と__del__」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMojo Academyレッスンでコードを書いて実行できますか?
はい。すべてのMojo Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。