diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 7962f42..bfa291f 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -23,7 +23,7 @@ * [字串](strings.md) * [泛型](generics.md) * [Traits](traits.md) - * [Drop](drop.md) + * [丟棄](drop.md) * [if let](if-let.md) * [Trait Objects](trait-objects.md) * [Closures](closures.md) diff --git a/src/drop.md b/src/drop.md index 7dd3db0..a00324f 100644 --- a/src/drop.md +++ b/src/drop.md @@ -1,8 +1,7 @@ -% Drop +% 丟棄 -Now that we’ve discussed traits, let’s talk about a particular trait provided -by the Rust standard library, [`Drop`][drop]. The `Drop` trait provides a way -to run some code when a value goes out of scope. For example: +基於我們已經討論過特徵了,現在讓我們一起來了解由Rust語言標準庫提供的特殊的特徵—— [`Drop`(丟棄)][drop]。 +丟棄(drop)的特徵(trait)是由一個值離開作用域時觸發的方法,譬如說: [drop]: ../std/ops/trait.Drop.html @@ -23,13 +22,11 @@ fn main() { } // x goes out of scope here ``` -When `x` goes out of scope at the end of `main()`, the code for `Drop` will -run. `Drop` has one method, which is also called `drop()`. It takes a mutable -reference to `self`. +當變數 `x` 離開它的作用域 `main()` 的底部的時候, 丟棄 `Drop` 的代碼就被觸發了。 +丟棄 `Drop` 有一個方法也被寫作 `drop()`。它用來回去一個自身 `self` 的可變引用。 -That’s it! The mechanics of `Drop` are very simple, but there are some -subtleties. For example, values are dropped in the opposite order they are -declared. Here’s another example: +正因如此,丟棄 `Drop` 的運行原理非常簡單。只是還有一些細節問題: +譬如說值會被以它們宣告的相反順序觸發丟棄(drop)的過程,譬如說: ```rust struct Firework { @@ -48,21 +45,20 @@ fn main() { } ``` -This will output: +輸出結果: ```text BOOM times 100!!! BOOM times 1!!! ``` -The TNT goes off before the firecracker does, because it was declared -afterwards. Last in, first out. +由於 TNT 在 firecracker 之後被聲明,所以 TNT 在 firecracker 之前離開作用域。 + +那麼 `Drop` 有什麼好處呢?通常情況下 `Drop` 被用來清理和 `struct` 關聯得到資源。 +譬如說 [`Arc` 型別][arc] 是一個引用計數型別。 +當 `Drop` 被調用的時候,它就會減少引用計數。 +此外,如果引用的總數為零,底層的值將會被擦除。 -So what is `Drop` good for? Generally, `Drop` is used to clean up any resources -associated with a `struct`. For example, the [`Arc` type][arc] is a -reference-counted type. When `Drop` is called, it will decrement the reference -count, and if the total number of references is zero, will clean up the -underlying value. [arc]: ../std/sync/struct.Arc.html