diff --git a/po/zh-TW.po b/po/zh-TW.po index dcbdec0b..9d2b2fda 100644 --- a/po/zh-TW.po +++ b/po/zh-TW.po @@ -1,7 +1,7 @@ msgid "" msgstr "" "Project-Id-Version: Comprehensive Rust 🦀\n" -"POT-Creation-Date: 2023-09-11 10:37-0700\n" +"POT-Creation-Date: 2024-03-06T16:11:58-08:00\n" "PO-Revision-Date: 2023-10-09 19:59-0700\n" "Last-Translator: \n" "Language-Team: \n" @@ -12,1082 +12,1361 @@ msgstr "" "Plural-Forms: nplurals=1; plural=0;\n" "X-Generator: Poedit 3.4\n" -#: src/SUMMARY.md:4 src/index.md:1 +#: src/SUMMARY.md src/index.md msgid "Welcome to Comprehensive Rust 🦀" msgstr "歡迎參加 Comprehensive Rust 🦀 課程" -#: src/SUMMARY.md:4 src/running-the-course.md:1 +#: src/SUMMARY.md src/running-the-course.md msgid "Running the Course" msgstr "講授課程" -#: src/SUMMARY.md:5 src/running-the-course/course-structure.md:1 +#: src/SUMMARY.md src/running-the-course/course-structure.md msgid "Course Structure" msgstr "課程架構" -#: src/SUMMARY.md:6 src/running-the-course/keyboard-shortcuts.md:1 +#: src/SUMMARY.md src/running-the-course/keyboard-shortcuts.md msgid "Keyboard Shortcuts" msgstr "鍵盤快速鍵" -#: src/SUMMARY.md:7 src/running-the-course/translations.md:1 +#: src/SUMMARY.md src/running-the-course/translations.md msgid "Translations" msgstr "翻譯" -#: src/SUMMARY.md:8 src/cargo.md:1 +#: src/SUMMARY.md src/cargo.md msgid "Using Cargo" msgstr "使用 Cargo" -#: src/SUMMARY.md:10 +#: src/SUMMARY.md msgid "Rust Ecosystem" msgstr "Rust 生態系統" -#: src/SUMMARY.md:11 +#: src/SUMMARY.md msgid "Code Samples" msgstr "程式碼範例" -#: src/SUMMARY.md:12 +#: src/SUMMARY.md msgid "Running Cargo Locally" msgstr "在本機執行 Cargo" -#: src/SUMMARY.md:15 +#: src/SUMMARY.md msgid "Day 1: Morning" msgstr "第 1 天:上午" -#: src/SUMMARY.md:19 src/SUMMARY.md:79 src/SUMMARY.md:134 src/SUMMARY.md:192 -#: src/SUMMARY.md:218 src/SUMMARY.md:268 +#: src/SUMMARY.md msgid "Welcome" msgstr "歡迎" -#: src/SUMMARY.md:20 src/welcome-day-1/what-is-rust.md:1 +#: src/SUMMARY.md src/hello-world.md src/types-and-values/hello-world.md +msgid "Hello, World" +msgstr "Hello, World" + +#: src/SUMMARY.md src/hello-world/what-is-rust.md msgid "What is Rust?" msgstr "什麼是 Rust?" -#: src/SUMMARY.md:21 src/hello-world.md:1 -msgid "Hello World!" -msgstr "Hello World!" +#: src/SUMMARY.md src/hello-world/benefits.md +msgid "Benefits of Rust" +msgstr "Rust 的優點" -#: src/SUMMARY.md:22 src/hello-world/small-example.md:1 -msgid "Small Example" -msgstr "簡短範例" +#: src/SUMMARY.md src/hello-world/playground.md +msgid "Playground" +msgstr "Playground" -#: src/SUMMARY.md:23 src/why-rust.md:1 -msgid "Why Rust?" -msgstr "為什麼要使用 Rust?" +#: src/SUMMARY.md src/types-and-values.md +msgid "Types and Values" +msgstr "型別和值" -#: src/SUMMARY.md:24 src/why-rust/compile-time.md:1 -msgid "Compile Time Guarantees" -msgstr "編譯時期保證" - -#: src/SUMMARY.md:25 src/why-rust/runtime.md:1 -msgid "Runtime Guarantees" -msgstr "執行時期保證" - -#: src/SUMMARY.md:26 src/why-rust/modern.md:1 -msgid "Modern Features" -msgstr "新潮的功能" - -#: src/SUMMARY.md:27 src/basic-syntax.md:1 -msgid "Basic Syntax" -msgstr "基本語法" - -#: src/SUMMARY.md:28 src/basic-syntax/scalar-types.md:1 -msgid "Scalar Types" -msgstr "純量型別" - -#: src/SUMMARY.md:29 src/basic-syntax/compound-types.md:1 -msgid "Compound Types" -msgstr "複合型別" - -#: src/SUMMARY.md:30 src/basic-syntax/references.md:1 -msgid "References" -msgstr "參照" - -#: src/SUMMARY.md:31 src/basic-syntax/references-dangling.md:1 -msgid "Dangling References" -msgstr "迷途參照" - -#: src/SUMMARY.md:32 src/basic-syntax/slices.md:1 -msgid "Slices" -msgstr "切片" - -#: src/SUMMARY.md:33 -msgid "String vs str" -msgstr "String 和 str" - -#: src/SUMMARY.md:34 src/basic-syntax/functions.md:1 -msgid "Functions" -msgstr "函式" - -#: src/SUMMARY.md:35 src/basic-syntax/rustdoc.md:1 -msgid "Rustdoc" -msgstr "Rustdoc" - -#: src/SUMMARY.md:36 src/SUMMARY.md:102 src/basic-syntax/methods.md:1 -#: src/methods.md:1 -msgid "Methods" -msgstr "方法" - -#: src/SUMMARY.md:37 -msgid "Overloading" -msgstr "超載" - -#: src/SUMMARY.md:38 src/SUMMARY.md:71 src/SUMMARY.md:105 src/SUMMARY.md:125 -#: src/SUMMARY.md:154 src/SUMMARY.md:184 src/SUMMARY.md:211 src/SUMMARY.md:232 -#: src/SUMMARY.md:260 src/SUMMARY.md:282 src/SUMMARY.md:303 -#: src/exercises/android/morning.md:1 src/exercises/bare-metal/morning.md:1 -#: src/exercises/bare-metal/afternoon.md:1 -#: src/exercises/concurrency/morning.md:1 -#: src/exercises/concurrency/afternoon.md:1 -msgid "Exercises" -msgstr "練習" - -#: src/SUMMARY.md:39 src/exercises/day-1/implicit-conversions.md:1 -msgid "Implicit Conversions" -msgstr "隱含轉換" - -#: src/SUMMARY.md:40 -msgid "Arrays and for Loops" -msgstr "陣列和 for 迴圈" - -#: src/SUMMARY.md:42 -msgid "Day 1: Afternoon" -msgstr "第 1 天:下午" - -#: src/SUMMARY.md:52 src/basic-syntax/variables.md:1 +#: src/SUMMARY.md src/types-and-values/variables.md msgid "Variables" msgstr "變數" -#: src/SUMMARY.md:53 src/basic-syntax/type-inference.md:1 +#: src/SUMMARY.md src/types-and-values/values.md +msgid "Values" +msgstr "值" + +#: src/SUMMARY.md src/types-and-values/arithmetic.md +msgid "Arithmetic" +msgstr "算術" + +#: src/SUMMARY.md src/types-and-values/strings.md +msgid "Strings" +msgstr "字串 (String)" + +#: src/SUMMARY.md src/types-and-values/inference.md msgid "Type Inference" msgstr "型別推斷" -#: src/SUMMARY.md:54 -msgid "static & const" -msgstr "靜態和常數" +#: src/SUMMARY.md src/types-and-values/exercise.md +msgid "Exercise: Fibonacci" +msgstr "練習:費波那契數列" -#: src/SUMMARY.md:55 src/basic-syntax/scopes-shadowing.md:1 +#: src/SUMMARY.md src/types-and-values/solution.md +#: src/control-flow-basics/solution.md src/tuples-and-arrays/solution.md +#: src/references/solution.md src/user-defined-types/solution.md +#: src/pattern-matching/solution.md src/methods-and-traits/solution.md +#: src/generics/solution.md src/std-types/solution.md +#: src/std-traits/solution.md src/memory-management/solution.md +#: src/smart-pointers/solution.md src/borrowing/solution.md +#: src/slices-and-lifetimes/solution.md src/iterators/solution.md +#: src/modules/solution.md src/testing/solution.md +#: src/error-handling/solution.md src/unsafe-rust/solution.md +msgid "Solution" +msgstr "解決方案" + +#: src/SUMMARY.md src/control-flow-basics.md +msgid "Control Flow Basics" +msgstr "基本的控制流程概念" + +#: src/SUMMARY.md +#, fuzzy +msgid "`if` Expressions" +msgstr "`if` 表達式" + +#: src/SUMMARY.md src/control-flow-basics/loops.md +#, fuzzy +msgid "Loops" +msgstr "`for` 迴圈" + +#: src/SUMMARY.md src/control-flow-basics/loops/for.md +msgid "`for`" +msgstr "`for`" + +#: src/SUMMARY.md src/control-flow-basics/loops/loop.md +msgid "`loop`" +msgstr "`loop` 迴圈" + +#: src/SUMMARY.md src/control-flow-basics/break-continue.md +msgid "`break` and `continue`" +msgstr "`break` 和 `continue`" + +#: src/SUMMARY.md src/control-flow-basics/break-continue/labels.md +msgid "Labels" +msgstr "標籤" + +#: src/SUMMARY.md src/control-flow-basics/blocks-and-scopes.md +msgid "Blocks and Scopes" +msgstr "區塊 (block) 和範疇 (scope)" + +#: src/SUMMARY.md src/control-flow-basics/blocks-and-scopes/scopes.md msgid "Scopes and Shadowing" msgstr "範圍和遮蔽" -#: src/SUMMARY.md:47 src/memory-management.md:1 -msgid "Memory Management" -msgstr "記憶體管理" +#: src/SUMMARY.md src/control-flow-basics/functions.md +msgid "Functions" +msgstr "函式" -#: src/SUMMARY.md:82 -msgid "Stack vs Heap" -msgstr "堆疊和堆積" +#: src/SUMMARY.md src/control-flow-basics/macros.md +msgid "Macros" +msgstr "巨集" -#: src/SUMMARY.md:49 src/memory-management/stack.md:1 -msgid "Stack Memory" -msgstr "堆疊記憶體" +#: src/SUMMARY.md src/control-flow-basics/exercise.md +msgid "Exercise: Collatz Sequence" +msgstr "練習:考拉茲序列" -#: src/SUMMARY.md:50 src/memory-management/manual.md:1 -msgid "Manual Memory Management" -msgstr "手動記憶體管理" +#: src/SUMMARY.md +msgid "Day 1: Afternoon" +msgstr "第 1 天:下午" -#: src/SUMMARY.md:51 src/memory-management/scope-based.md:1 -msgid "Scope-Based Memory Management" -msgstr "作用域式記憶體管理" +#: src/SUMMARY.md src/tuples-and-arrays.md +msgid "Tuples and Arrays" +msgstr "元組和陣列" -#: src/SUMMARY.md:86 -msgid "Garbage Collection" -msgstr "垃圾回收" +#: src/SUMMARY.md src/tuples-and-arrays/arrays.md +msgid "Arrays" +msgstr "陣列" -#: src/SUMMARY.md:87 -msgid "Rust Memory Management" -msgstr "Rust 記憶體管理" +#: src/SUMMARY.md src/tuples-and-arrays/tuples.md +msgid "Tuples" +msgstr "元組" -#: src/SUMMARY.md:54 src/memory-management/comparison.md:1 -msgid "Comparison" -msgstr "比較" +#: src/SUMMARY.md src/tuples-and-arrays/iteration.md +#, fuzzy +msgid "Array Iteration" +msgstr "疊代器" -#: src/SUMMARY.md:55 src/ownership.md:1 -msgid "Ownership" -msgstr "所有權" +#: src/SUMMARY.md src/tuples-and-arrays/destructuring.md +#, fuzzy +msgid "Patterns and Destructuring" +msgstr "模式配對" -#: src/SUMMARY.md:56 src/ownership/move-semantics.md:1 -msgid "Move Semantics" -msgstr "移動語意" +#: src/SUMMARY.md src/tuples-and-arrays/exercise.md +msgid "Exercise: Nested Arrays" +msgstr "練習:巢狀陣列" -#: src/SUMMARY.md:57 src/ownership/moved-strings-rust.md:1 -msgid "Moved Strings in Rust" -msgstr "Rust 中移動的字串" +#: src/SUMMARY.md src/references.md +msgid "References" +msgstr "參照" -#: src/SUMMARY.md:58 src/ownership/double-free-modern-cpp.md:1 -msgid "Double Frees in Modern C++" -msgstr "現代 C++ 中的雙重釋放" +#: src/SUMMARY.md src/references/shared.md +#, fuzzy +msgid "Shared References" +msgstr "共用列舉" -#: src/SUMMARY.md:59 src/ownership/moves-function-calls.md:1 -msgid "Moves in Function Calls" -msgstr "函式呼叫中的移動" +#: src/SUMMARY.md src/references/exclusive.md +#, fuzzy +msgid "Exclusive References" +msgstr "迷途參照" -#: src/SUMMARY.md:60 src/ownership/copy-clone.md:1 -msgid "Copying and Cloning" -msgstr "複製和克隆" +#: src/SUMMARY.md src/references/exercise.md +msgid "Exercise: Geometry" +msgstr "練習:幾何圖形" -#: src/SUMMARY.md:61 src/ownership/borrowing.md:1 -msgid "Borrowing" -msgstr "借用" +#: src/SUMMARY.md src/user-defined-types.md +msgid "User-Defined Types" +msgstr "使用者定義的型別" -#: src/SUMMARY.md:62 src/ownership/shared-unique-borrows.md:1 -msgid "Shared and Unique Borrows" -msgstr "共用借用和專屬借用" - -#: src/SUMMARY.md:63 src/ownership/lifetimes.md:1 -msgid "Lifetimes" -msgstr "生命週期" - -#: src/SUMMARY.md:64 src/ownership/lifetimes-function-calls.md:1 -msgid "Lifetimes in Function Calls" -msgstr "函式呼叫中的生命週期" - -#: src/SUMMARY.md:65 src/ownership/lifetimes-data-structures.md:1 -msgid "Lifetimes in Data Structures" -msgstr "資料結構中的生命週期" - -#: src/exercises/day-2/solutions-morning.md:3 -msgid "Designing a Library" -msgstr "設計程式庫" - -#: src/SUMMARY.md:126 src/exercises/day-2/iterators-and-ownership.md:1 -msgid "Iterators and Ownership" -msgstr "疊代器和擁有權" - -#: src/SUMMARY.md:75 -msgid "Day 2: Morning" -msgstr "第 2 天:上午" - -#: src/SUMMARY.md:76 src/structs.md:1 -msgid "Structs" +#: src/SUMMARY.md src/user-defined-types/named-structs.md +#, fuzzy +msgid "Named Structs" msgstr "結構體" -#: src/SUMMARY.md:77 src/structs/tuple-structs.md:1 +#: src/SUMMARY.md src/user-defined-types/tuple-structs.md msgid "Tuple Structs" msgstr "元組結構體" -#: src/SUMMARY.md:78 src/structs/field-shorthand.md:1 -msgid "Field Shorthand Syntax" -msgstr "欄位簡寫語法" - -#: src/SUMMARY.md:79 src/enums.md:1 +#: src/SUMMARY.md src/user-defined-types/enums.md +#: src/pattern-matching/destructuring.md msgid "Enums" msgstr "列舉" -#: src/SUMMARY.md:80 src/enums/variant-payloads.md:1 -msgid "Variant Payloads" -msgstr "變體負載" +#: src/SUMMARY.md src/user-defined-types/static-and-const.md +#, fuzzy +msgid "Static and Const" +msgstr "靜態和常數" -#: src/SUMMARY.md:81 src/enums/sizes.md:1 -msgid "Enum Sizes" -msgstr "列舉大小" +#: src/SUMMARY.md src/user-defined-types/aliases.md +msgid "Type Aliases" +msgstr "型別別名" -#: src/SUMMARY.md:103 src/methods/receiver.md:1 -msgid "Method Receiver" -msgstr "方法接收器" +#: src/SUMMARY.md src/user-defined-types/exercise.md +msgid "Exercise: Elevator Events" +msgstr "練習:電梯事件" -#: src/SUMMARY.md:84 src/SUMMARY.md:159 src/SUMMARY.md:272 -#: src/methods/example.md:1 src/concurrency/shared_state/example.md:1 -msgid "Example" -msgstr "範例" +#: src/SUMMARY.md +msgid "Day 2: Morning" +msgstr "第 2 天:上午" -#: src/SUMMARY.md:65 src/pattern-matching.md:1 +#: src/SUMMARY.md src/pattern-matching.md msgid "Pattern Matching" msgstr "模式配對" -#: src/SUMMARY.md:66 src/pattern-matching/destructuring-enums.md:1 -msgid "Destructuring Enums" +#: src/SUMMARY.md src/pattern-matching/match.md +msgid "Matching Values" +msgstr "" + +#: src/SUMMARY.md src/pattern-matching/destructuring.md +#, fuzzy +msgid "Destructuring" msgstr "解構列舉" -#: src/SUMMARY.md:67 src/pattern-matching/destructuring-structs.md:1 -msgid "Destructuring Structs" -msgstr "解構結構體" - -#: src/SUMMARY.md:68 src/pattern-matching/destructuring-arrays.md:1 -msgid "Destructuring Arrays" -msgstr "解構陣列" - -#: src/SUMMARY.md:69 src/pattern-matching/match-guards.md:1 -msgid "Match Guards" -msgstr "配對守衛" - -#: src/SUMMARY.md:107 src/exercises/day-2/health-statistics.md:1 -msgid "Health Statistics" -msgstr "健康統計資料" - -#: src/SUMMARY.md:156 src/exercises/day-3/solutions-morning.md:175 -msgid "Points and Polygons" -msgstr "點和多邊形" - -#: src/SUMMARY.md:109 -msgid "Day 2: Afternoon" -msgstr "第 2 天:下午" - -#: src/SUMMARY.md:96 src/SUMMARY.md:286 src/control-flow.md:1 -msgid "Control Flow" +#: src/SUMMARY.md src/pattern-matching/let-control-flow.md +#, fuzzy +msgid "Let Control Flow" msgstr "控制流程" -#: src/SUMMARY.md:97 src/control-flow/blocks.md:1 -msgid "Blocks" -msgstr "區塊" +#: src/SUMMARY.md src/pattern-matching/exercise.md +msgid "Exercise: Expression Evaluation" +msgstr "練習:運算式求值" -#: src/SUMMARY.md:98 -msgid "if expressions" -msgstr "if 表達式" +#: src/SUMMARY.md src/methods-and-traits.md +#, fuzzy +msgid "Methods and Traits" +msgstr "Read 和 Write" -#: src/SUMMARY.md:61 -msgid "if let expressions" -msgstr "if let 運算式" +#: src/SUMMARY.md src/methods-and-traits/methods.md +msgid "Methods" +msgstr "方法" -#: src/SUMMARY.md:48 -msgid "while expressions" -msgstr "while 運算式" - -#: src/SUMMARY.md:62 -msgid "while let expressions" -msgstr "while let 運算式" - -#: src/SUMMARY.md:47 -msgid "for expressions" -msgstr "for 運算式" - -#: src/SUMMARY.md:50 -msgid "loop expressions" -msgstr "loop 運算式" - -#: src/SUMMARY.md:63 -msgid "match expressions" -msgstr "match 運算式" - -#: src/SUMMARY.md:49 -msgid "break & continue" -msgstr "break 和 continue" - -#: src/SUMMARY.md:106 src/std.md:1 -msgid "Standard Library" -msgstr "標準函式庫" - -#: src/SUMMARY.md:112 -msgid "Option and Result" -msgstr "Option 和 Result" - -#: src/SUMMARY.md:108 src/std/string.md:1 -msgid "String" -msgstr "String" - -#: src/SUMMARY.md:114 -msgid "Vec" -msgstr "Vec" - -#: src/SUMMARY.md:115 -msgid "HashMap" -msgstr "HashMap" - -#: src/SUMMARY.md:116 -msgid "Box" -msgstr "Box" - -#: src/SUMMARY.md:117 -msgid "Recursive Data Types" -msgstr "遞迴資料型別" - -#: src/SUMMARY.md:113 src/std/box-niche.md:1 -msgid "Niche Optimization" -msgstr "區位最佳化" - -#: src/SUMMARY.md:119 -msgid "Rc" -msgstr "Rc" - -#: src/SUMMARY.md:121 src/modules.md:1 -msgid "Modules" -msgstr "模組" - -#: src/SUMMARY.md:122 src/modules/visibility.md:1 -msgid "Visibility" -msgstr "能見度" - -#: src/SUMMARY.md:123 src/modules/paths.md:1 -msgid "Paths" -msgstr "路徑" - -#: src/SUMMARY.md:124 src/modules/filesystem.md:1 -msgid "Filesystem Hierarchy" -msgstr "檔案系統階層" - -#: src/SUMMARY.md:72 src/exercises/day-1/luhn.md:1 -#: src/exercises/day-1/solutions-afternoon.md:3 -msgid "Luhn Algorithm" -msgstr "盧恩演算法" - -#: src/SUMMARY.md:127 src/exercises/day-2/strings-iterators.md:1 -#: src/exercises/day-2/solutions-afternoon.md:3 -msgid "Strings and Iterators" -msgstr "字串和疊代器" - -#: src/SUMMARY.md:130 -msgid "Day 3: Morning" -msgstr "第 3 天:上午" - -#: src/SUMMARY.md:129 src/generics.md:1 -msgid "Generics" -msgstr "泛型" - -#: src/SUMMARY.md:130 src/generics/data-types.md:1 -msgid "Generic Data Types" -msgstr "泛型資料型別" - -#: src/SUMMARY.md:131 src/generics/methods.md:1 -msgid "Generic Methods" -msgstr "泛型方法" - -#: src/SUMMARY.md:132 src/generics/monomorphization.md:1 -msgid "Monomorphization" -msgstr "單型化" - -#: src/SUMMARY.md:133 src/traits.md:1 +#: src/SUMMARY.md src/methods-and-traits/traits.md msgid "Traits" msgstr "特徵" -#: src/SUMMARY.md:134 src/traits/trait-objects.md:1 -msgid "Trait Objects" -msgstr "特徵物件" +#: src/SUMMARY.md +#, fuzzy +msgid "Implmementing Traits" +msgstr "實作不安全的特徵" -#: src/SUMMARY.md:135 src/traits/deriving-traits.md:1 -msgid "Deriving Traits" +#: src/SUMMARY.md src/methods-and-traits/traits/associated-types.md +msgid "Associated Types" +msgstr "" + +#: src/SUMMARY.md src/methods-and-traits/deriving.md +#, fuzzy +msgid "Deriving" msgstr "衍生特徵" -#: src/SUMMARY.md:136 src/traits/default-methods.md:1 -msgid "Default Methods" -msgstr "預設方法" +#: src/SUMMARY.md src/methods-and-traits/exercise.md +msgid "Exercise: Generic Logger" +msgstr "練習:泛型 Logger" -#: src/SUMMARY.md:137 src/traits/trait-bounds.md:1 +#: src/SUMMARY.md src/generics.md +msgid "Generics" +msgstr "泛型" + +#: src/SUMMARY.md src/generics/generic-functions.md +#, fuzzy +msgid "Generic Functions" +msgstr "Extern 函式" + +#: src/SUMMARY.md src/generics/generic-data.md +msgid "Generic Data Types" +msgstr "泛型資料型別" + +#: src/SUMMARY.md src/generics/trait-bounds.md msgid "Trait Bounds" msgstr "特徵界限" -#: src/SUMMARY.md:144 -msgid "impl Trait" -msgstr "impl Trait" +#: src/SUMMARY.md src/generics/impl-trait.md +msgid "`impl Trait`" +msgstr "`impl Trait`" -#: src/SUMMARY.md:139 src/traits/important-traits.md:1 -msgid "Important Traits" -msgstr "重要特徵" +#: src/SUMMARY.md src/generics/exercise.md +msgid "Exercise: Generic `min`" +msgstr "練習:泛型 `min`" -#: src/SUMMARY.md:146 -msgid "Iterator" +#: src/SUMMARY.md +msgid "Day 2: Afternoon" +msgstr "第 2 天:下午" + +#: src/SUMMARY.md src/std-types.md +#, fuzzy +msgid "Standard Library Types" +msgstr "標準函式庫" + +#: src/SUMMARY.md src/std-types/std.md +msgid "Standard Library" +msgstr "標準函式庫" + +#: src/SUMMARY.md src/std-types/docs.md +#, fuzzy +msgid "Documentation" +msgstr "說明文件測試" + +#: src/SUMMARY.md +msgid "`Option`" +msgstr "`Option`" + +#: src/SUMMARY.md +msgid "`Result`" +msgstr "`Result`" + +#: src/SUMMARY.md src/android/aidl/types/primitives.md +#: src/android/interoperability/cpp/type-mapping.md +msgid "`String`" +msgstr "`String`" + +#: src/SUMMARY.md src/std-types/vec.md +msgid "`Vec`" +msgstr "`Vec`" + +#: src/SUMMARY.md src/std-types/hashmap.md src/bare-metal/no_std.md +msgid "`HashMap`" +msgstr "`HashMap`" + +#: src/SUMMARY.md src/std-types/exercise.md +msgid "Exercise: Counter" +msgstr "練習:計數器" + +#: src/SUMMARY.md src/std-traits.md +#, fuzzy +msgid "Standard Library Traits" +msgstr "標準函式庫" + +#: src/SUMMARY.md src/std-traits/comparisons.md src/async.md +msgid "Comparisons" +msgstr "比較" + +#: src/SUMMARY.md src/std-traits/operators.md +#, fuzzy +msgid "Operators" msgstr "疊代器" -#: src/SUMMARY.md:141 src/traits/from-iterator.md:1 -msgid "FromIterator" -msgstr "FromIterator" +#: src/SUMMARY.md src/std-traits/from-and-into.md +msgid "`From` and `Into`" +msgstr "`From` 和 `Into`" -#: src/SUMMARY.md:148 -msgid "From and Into" -msgstr "From 和 Into" +#: src/SUMMARY.md src/std-traits/casting.md +#, fuzzy +msgid "Casting" +msgstr "測試" -#: src/SUMMARY.md:149 -msgid "Read and Write" -msgstr "Read 和 Write" +#: src/SUMMARY.md src/std-traits/read-and-write.md +msgid "`Read` and `Write`" +msgstr "`Read` 和 `Write`" -#: src/SUMMARY.md:150 -msgid "Drop" -msgstr "Drop" +#: src/SUMMARY.md +msgid "`Default`, struct update syntax" +msgstr "`Default` (結構體更新語法)" -#: src/SUMMARY.md:151 -msgid "Default" -msgstr "Default" +#: src/SUMMARY.md src/std-traits/closures.md +msgid "Closures" +msgstr "閉包" -#: src/SUMMARY.md:152 -msgid "Operators: Add, Mul, ..." -msgstr "運算子:Add、Mul、..." +#: src/SUMMARY.md src/std-traits/exercise.md +msgid "Exercise: ROT13" +msgstr "練習:ROT13 (迴轉13位)" -#: src/SUMMARY.md:153 -msgid "Closures: Fn, FnMut, FnOnce" -msgstr "閉包:Fn、FnMut、FnOnce" +#: src/SUMMARY.md +msgid "Day 3: Morning" +msgstr "第 3 天:上午" -#: src/SUMMARY.md:155 src/exercises/day-3/simple-gui.md:1 -#: src/exercises/day-3/solutions-morning.md:3 -msgid "A Simple GUI Library" -msgstr "簡易 GUI 程式庫" +#: src/SUMMARY.md src/memory-management.md +msgid "Memory Management" +msgstr "記憶體管理" -#: src/SUMMARY.md:158 +#: src/SUMMARY.md src/memory-management/review.md +msgid "Review of Program Memory" +msgstr "檢查程式記憶體" + +#: src/SUMMARY.md src/memory-management/approaches.md +#, fuzzy +msgid "Approaches to Memory Management" +msgstr "自動記憶體管理" + +#: src/SUMMARY.md src/memory-management/ownership.md +msgid "Ownership" +msgstr "所有權" + +#: src/SUMMARY.md src/memory-management/move.md +msgid "Move Semantics" +msgstr "移動語意" + +#: src/SUMMARY.md +msgid "`Clone`" +msgstr "`Clone`" + +#: src/SUMMARY.md src/memory-management/copy-types.md +msgid "Copy Types" +msgstr "Copy 型別" + +#: src/SUMMARY.md +msgid "`Drop`" +msgstr "`Drop`" + +#: src/SUMMARY.md src/memory-management/exercise.md +msgid "Exercise: Builder Type" +msgstr "練習:建構工具型別" + +#: src/SUMMARY.md src/smart-pointers.md +msgid "Smart Pointers" +msgstr "智慧指標" + +#: src/SUMMARY.md src/smart-pointers/box.md +#: src/android/interoperability/cpp/type-mapping.md +msgid "`Box`" +msgstr "`Box`" + +#: src/SUMMARY.md src/smart-pointers/rc.md +msgid "`Rc`" +msgstr "`Rc`" + +#: src/SUMMARY.md src/smart-pointers/trait-objects.md +msgid "Trait Objects" +msgstr "特徵物件" + +#: src/SUMMARY.md src/smart-pointers/exercise.md +msgid "Exercise: Binary Tree" +msgstr "練習:二元樹" + +#: src/SUMMARY.md msgid "Day 3: Afternoon" msgstr "第 3 天:下午" -#: src/SUMMARY.md:153 src/error-handling.md:1 -msgid "Error Handling" -msgstr "錯誤處理" +#: src/SUMMARY.md src/borrowing.md +msgid "Borrowing" +msgstr "借用" -#: src/SUMMARY.md:154 src/error-handling/panics.md:1 -msgid "Panics" -msgstr "恐慌" +#: src/SUMMARY.md src/borrowing/shared.md +#, fuzzy +msgid "Borrowing a Value" +msgstr "借用" -#: src/SUMMARY.md:162 -msgid "Catching Stack Unwinding" -msgstr "捕獲解開堆疊的動作" +#: src/SUMMARY.md src/borrowing/borrowck.md +#, fuzzy +msgid "Borrow Checking" +msgstr "借用" -#: src/SUMMARY.md:163 -msgid "Structured Error Handling" -msgstr "結構化錯誤處理" +#: src/SUMMARY.md src/borrowing/interior-mutability.md +msgid "Interior Mutability" +msgstr "內部可變性 (Interior Mutability)" -#: src/SUMMARY.md:164 -msgid "Propagating Errors with ?" -msgstr "使用 ? 傳播錯誤" +#: src/SUMMARY.md src/borrowing/exercise.md +msgid "Exercise: Health Statistics" +msgstr "練習:衛生統計資料" -#: src/SUMMARY.md:158 src/error-handling/converting-error-types.md:1 -#: src/error-handling/converting-error-types-example.md:1 -msgid "Converting Error Types" -msgstr "轉換錯誤型別" +#: src/SUMMARY.md src/slices-and-lifetimes.md +#, fuzzy +msgid "Slices and Lifetimes" +msgstr "生命週期" -#: src/SUMMARY.md:160 src/error-handling/deriving-error-enums.md:1 -msgid "Deriving Error Enums" -msgstr "推導錯誤列舉" +#: src/SUMMARY.md +#, fuzzy +msgid "Slices: `&[T]`" +msgstr "切片" -#: src/SUMMARY.md:161 src/error-handling/dynamic-errors.md:1 -msgid "Dynamic Error Types" -msgstr "動態錯誤型別" +#: src/SUMMARY.md src/slices-and-lifetimes/str.md +#, fuzzy +msgid "String References" +msgstr "迷途參照" -#: src/SUMMARY.md:162 src/error-handling/error-contexts.md:1 -msgid "Adding Context to Errors" -msgstr "為錯誤添加背景資訊" +#: src/SUMMARY.md src/slices-and-lifetimes/lifetime-annotations.md +#, fuzzy +msgid "Lifetime Annotations" +msgstr "函式呼叫中的生命週期" -#: src/SUMMARY.md:163 src/testing.md:1 +#: src/SUMMARY.md +#, fuzzy +msgid "Lifetime Elision" +msgstr "生命週期" + +#: src/SUMMARY.md +#, fuzzy +msgid "Struct Lifetimes" +msgstr "生命週期" + +#: src/SUMMARY.md src/slices-and-lifetimes/exercise.md +msgid "Exercise: Protobuf Parsing" +msgstr "練習:Protobuf 剖析" + +#: src/SUMMARY.md +msgid "Day 4: Morning" +msgstr "第 4 天:上午" + +#: src/SUMMARY.md src/iterators.md +msgid "Iterators" +msgstr "疊代器" + +#: src/SUMMARY.md src/iterators/iterator.md src/bare-metal/no_std.md +msgid "`Iterator`" +msgstr "`Iterator`" + +#: src/SUMMARY.md src/iterators/intoiterator.md +msgid "`IntoIterator`" +msgstr "`IntoIterator`" + +#: src/SUMMARY.md +msgid "`FromIterator`" +msgstr "`FromIterator`" + +#: src/SUMMARY.md src/iterators/exercise.md +msgid "Exercise: Iterator Method Chaining" +msgstr "練習:疊代器方法鏈結" + +#: src/SUMMARY.md src/modules.md src/modules/modules.md +msgid "Modules" +msgstr "模組" + +#: src/SUMMARY.md src/modules/filesystem.md +msgid "Filesystem Hierarchy" +msgstr "檔案系統階層" + +#: src/SUMMARY.md src/modules/visibility.md +msgid "Visibility" +msgstr "能見度" + +#: src/SUMMARY.md +msgid "`use`, `super`, `self`" +msgstr "`use`、`super`、`self`" + +#: src/SUMMARY.md src/modules/exercise.md +msgid "Exercise: Modules for a GUI Library" +msgstr "練習:GUI 程式庫的模組" + +#: src/SUMMARY.md src/testing.md src/chromium/testing.md msgid "Testing" msgstr "測試" -#: src/SUMMARY.md:164 src/testing/unit-tests.md:1 -msgid "Unit Tests" -msgstr "單元測試" - -#: src/SUMMARY.md:165 src/testing/test-modules.md:1 +#: src/SUMMARY.md msgid "Test Modules" msgstr "測試模組" -#: src/SUMMARY.md:166 src/testing/doc-tests.md:1 -msgid "Documentation Tests" -msgstr "說明文件測試" +#: src/SUMMARY.md src/testing/other.md +#, fuzzy +msgid "Other Types of Tests" +msgstr "其他資源" -#: src/SUMMARY.md:167 src/testing/integration-tests.md:1 -msgid "Integration Tests" -msgstr "整合測試" +#: src/SUMMARY.md src/testing/lints.md +msgid "Compiler Lints and Clippy" +msgstr "編譯器檢查 (Lint) 和 Clippy " -#: src/SUMMARY.md:175 src/bare-metal/useful-crates.md:1 -msgid "Useful crates" -msgstr "實用的 Crate" +#: src/SUMMARY.md src/testing/exercise.md +#, fuzzy +msgid "Exercise: Luhn Algorithm" +msgstr "盧恩演算法" -#: src/SUMMARY.md:169 src/unsafe.md:1 +#: src/SUMMARY.md +msgid "Day 4: Afternoon" +msgstr "第 4 天:下午" + +#: src/SUMMARY.md src/error-handling.md +msgid "Error Handling" +msgstr "錯誤處理" + +#: src/SUMMARY.md src/error-handling/panics.md +msgid "Panics" +msgstr "恐慌" + +#: src/SUMMARY.md src/error-handling/try.md +#, fuzzy +msgid "Try Operator" +msgstr "疊代器" + +#: src/SUMMARY.md src/error-handling/try-conversions.md +#, fuzzy +msgid "Try Conversions" +msgstr "隱含轉換" + +#: src/SUMMARY.md +#, fuzzy +msgid "`Error` Trait" +msgstr "`Drop` 特徵" + +#: src/SUMMARY.md src/error-handling/thiserror-and-anyhow.md +#, fuzzy +msgid "`thiserror` and `anyhow`" +msgstr "`From` 和 `Into`" + +#: src/SUMMARY.md +#, fuzzy +msgid "Exercise: Rewriting with `Result`" +msgstr "使用 `Result` 進行結構化錯誤處理" + +#: src/SUMMARY.md src/unsafe-rust.md src/unsafe-rust/unsafe.md msgid "Unsafe Rust" msgstr "不安全的 Rust" -#: src/SUMMARY.md:170 src/unsafe/raw-pointers.md:1 +#: src/SUMMARY.md +#, fuzzy +msgid "Unsafe" +msgstr "不安全的 Rust" + +#: src/SUMMARY.md src/unsafe-rust/dereferencing.md msgid "Dereferencing Raw Pointers" msgstr "對裸指標解參考" -#: src/SUMMARY.md:171 src/unsafe/mutable-static-variables.md:1 +#: src/SUMMARY.md src/unsafe-rust/mutable-static.md msgid "Mutable Static Variables" msgstr "可變的靜態變數" -#: src/SUMMARY.md:172 src/unsafe/unions.md:1 +#: src/SUMMARY.md src/unsafe-rust/unions.md msgid "Unions" msgstr "聯合體" -#: src/SUMMARY.md:173 src/unsafe/calling-unsafe-functions.md:1 -msgid "Calling Unsafe Functions" +#: src/SUMMARY.md src/unsafe-rust/unsafe-functions.md +#, fuzzy +msgid "Unsafe Functions" msgstr "呼叫不安全的函式" -#: src/SUMMARY.md:174 src/unsafe/writing-unsafe-functions.md:1 -msgid "Writing Unsafe Functions" -msgstr "編寫不安全的函式" - -#: src/SUMMARY.md:182 -msgid "Extern Functions" -msgstr "Extern 函式" - -#: src/SUMMARY.md:176 src/unsafe/unsafe-traits.md:1 -msgid "Implementing Unsafe Traits" +#: src/SUMMARY.md +#, fuzzy +msgid "Unsafe Traits" msgstr "實作不安全的特徵" -#: src/SUMMARY.md:185 src/exercises/day-3/safe-ffi-wrapper.md:1 -#: src/exercises/day-3/solutions-afternoon.md:3 -msgid "Safe FFI Wrapper" -msgstr "安全的 FFI 包裝函式" +#: src/SUMMARY.md +#, fuzzy +msgid "Exercise: FFI Wrapper" +msgstr "練習:封裝外部函式介面 (FFI)" -#: src/SUMMARY.md:181 src/SUMMARY.md:249 -#: src/running-the-course/course-structure.md:16 src/bare-metal/android.md:1 +#: src/SUMMARY.md src/bare-metal/android.md msgid "Android" msgstr "Android" -#: src/SUMMARY.md:193 src/android/setup.md:1 +#: src/SUMMARY.md src/android/setup.md src/chromium/setup.md msgid "Setup" msgstr "設定" -#: src/SUMMARY.md:187 src/android/build-rules.md:1 +#: src/SUMMARY.md src/android/build-rules.md msgid "Build Rules" msgstr "建構規則" -#: src/SUMMARY.md:195 +#: src/SUMMARY.md msgid "Binary" msgstr "二進位檔" -#: src/SUMMARY.md:196 +#: src/SUMMARY.md msgid "Library" msgstr "函式庫" -#: src/SUMMARY.md:197 src/android/aidl.md:1 +#: src/SUMMARY.md src/android/aidl.md msgid "AIDL" msgstr "AIDL" -#: src/SUMMARY.md:198 +#: src/SUMMARY.md src/android/aidl/birthday-service.md +msgid "Birthday Service Tutorial" +msgstr "" + +#: src/SUMMARY.md msgid "Interface" msgstr "介面" -#: src/SUMMARY.md:199 -msgid "Implementation" -msgstr "實作" +#: src/SUMMARY.md +msgid "Service API" +msgstr "" -#: src/SUMMARY.md:200 +#: src/SUMMARY.md +#, fuzzy +msgid "Service" +msgstr "伺服器" + +#: src/SUMMARY.md msgid "Server" msgstr "伺服器" -#: src/SUMMARY.md:201 src/android/aidl/deploy.md:1 +#: src/SUMMARY.md src/android/aidl/example-service/deploy.md msgid "Deploy" msgstr "部署" -#: src/SUMMARY.md:202 +#: src/SUMMARY.md msgid "Client" msgstr "用戶端" -#: src/SUMMARY.md:196 src/android/aidl/changing.md:1 +#: src/SUMMARY.md src/android/aidl/example-service/changing-definition.md msgid "Changing API" msgstr "改寫 API" -#: src/SUMMARY.md:204 src/SUMMARY.md:248 src/android/logging.md:1 -#: src/bare-metal/aps/logging.md:1 +#: src/SUMMARY.md +#, fuzzy +msgid "Updating Implementations" +msgstr "實作" + +#: src/SUMMARY.md +#, fuzzy +msgid "AIDL Types" +msgstr "類型" + +#: src/SUMMARY.md src/android/aidl/types/primitives.md +msgid "Primitive Types" +msgstr "" + +#: src/SUMMARY.md src/android/aidl/types/arrays.md +#, fuzzy +msgid "Array Types" +msgstr "陣列" + +#: src/SUMMARY.md src/android/aidl/types/objects.md +#, fuzzy +msgid "Sending Objects" +msgstr "特徵物件" + +#: src/SUMMARY.md src/android/aidl/types/parcelables.md +#, fuzzy +msgid "Parcelables" +msgstr "變數" + +#: src/SUMMARY.md src/android/aidl/types/file-descriptor.md +msgid "Sending Files" +msgstr "" + +#: src/SUMMARY.md src/android/testing/googletest.md +msgid "GoogleTest" +msgstr "GoogleTest" + +#: src/SUMMARY.md src/android/testing/mocking.md +msgid "Mocking" +msgstr "模擬 (Mocking)" + +#: src/SUMMARY.md src/android/logging.md src/bare-metal/aps/logging.md msgid "Logging" msgstr "記錄" -#: src/SUMMARY.md:205 src/android/interoperability.md:1 +#: src/SUMMARY.md src/android/interoperability.md msgid "Interoperability" msgstr "互通性" -#: src/SUMMARY.md:206 +#: src/SUMMARY.md msgid "With C" msgstr "與 C 的互通性" -#: src/SUMMARY.md:207 +#: src/SUMMARY.md msgid "Calling C with Bindgen" msgstr "使用 Bindgen 呼叫 C" -#: src/SUMMARY.md:208 +#: src/SUMMARY.md msgid "Calling Rust from C" msgstr "從 C 呼叫 Rust" -#: src/SUMMARY.md:209 src/android/interoperability/cpp.md:1 +#: src/SUMMARY.md src/android/interoperability/cpp.md msgid "With C++" msgstr "與 C++ 的互通性" -#: src/SUMMARY.md:210 +#: src/SUMMARY.md src/android/interoperability/cpp/bridge.md +#, fuzzy +msgid "The Bridge Module" +msgstr "測試模組" + +#: src/SUMMARY.md +msgid "Rust Bridge" +msgstr "Rust 橋接器" + +#: src/SUMMARY.md src/android/interoperability/cpp/generated-cpp.md +msgid "Generated C++" +msgstr "產生的 C++" + +#: src/SUMMARY.md +msgid "C++ Bridge" +msgstr "C++ 橋接器" + +#: src/SUMMARY.md src/android/interoperability/cpp/shared-types.md +#, fuzzy +msgid "Shared Types" +msgstr "共用型別" + +#: src/SUMMARY.md src/android/interoperability/cpp/shared-enums.md +msgid "Shared Enums" +msgstr "共用列舉" + +#: src/SUMMARY.md src/android/interoperability/cpp/rust-result.md +#, fuzzy +msgid "Rust Error Handling" +msgstr "錯誤處理" + +#: src/SUMMARY.md src/android/interoperability/cpp/cpp-exception.md +#, fuzzy +msgid "C++ Error Handling" +msgstr "錯誤處理" + +#: src/SUMMARY.md src/android/interoperability/cpp/type-mapping.md +msgid "Additional Types" +msgstr "其他型別" + +#: src/SUMMARY.md +msgid "Building for Android: C++" +msgstr "針對 Android 建構:C++" + +#: src/SUMMARY.md +msgid "Building for Android: Genrules" +msgstr "針對 Android 建構:Genrules" + +#: src/SUMMARY.md +msgid "Building for Android: Rust" +msgstr "針對 Android 建構:Rust" + +#: src/SUMMARY.md msgid "With Java" msgstr "與 Java 的互通性" -#: src/SUMMARY.md:214 +#: src/SUMMARY.md src/exercises/android/morning.md +#: src/exercises/bare-metal/morning.md src/exercises/bare-metal/afternoon.md +#: src/exercises/concurrency/morning.md src/exercises/concurrency/afternoon.md +msgid "Exercises" +msgstr "練習" + +#: src/SUMMARY.md +msgid "Chromium" +msgstr "Chromium" + +#: src/SUMMARY.md src/chromium/cargo.md +msgid "Comparing Chromium and Cargo Ecosystems" +msgstr "比較 Chromium 和 Cargo 的生態系統" + +#: src/SUMMARY.md +msgid "Policy" +msgstr "政策" + +#: src/SUMMARY.md +#, fuzzy +msgid "Unsafe Code" +msgstr "不安全的 Rust" + +#: src/SUMMARY.md src/chromium/build-rules/depending.md +msgid "Depending on Rust Code from Chromium C++" +msgstr "在 Chromium C++ 中使用 Rust 程式碼" + +#: src/SUMMARY.md src/chromium/build-rules/vscode.md +msgid "Visual Studio Code" +msgstr "Visual Studio Code" + +#: src/SUMMARY.md src/exercises/chromium/third-party.md +msgid "Exercise" +msgstr "練習" + +#: src/SUMMARY.md src/chromium/testing/rust-gtest-interop.md +msgid "`rust_gtest_interop` Library" +msgstr "`rust_gtest_interop` 程式庫" + +#: src/SUMMARY.md src/chromium/testing/build-gn.md +msgid "GN Rules for Rust Tests" +msgstr "Rust 測試適用的 GN 規則" + +#: src/SUMMARY.md src/chromium/testing/chromium-import-macro.md +msgid "`chromium::import!` Macro" +msgstr "`chromium::import!` 巨集" + +#: src/SUMMARY.md src/chromium/interoperability-with-cpp.md +#, fuzzy +msgid "Interoperability with C++" +msgstr "互通性" + +#: src/SUMMARY.md src/chromium/interoperability-with-cpp/example-bindings.md +#, fuzzy +msgid "Example Bindings" +msgstr "範例" + +#: src/SUMMARY.md src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "Limitations of CXX" +msgstr "CXX 的限制" + +#: src/SUMMARY.md src/chromium/interoperability-with-cpp/error-handling.md +#, fuzzy +msgid "CXX Error Handling" +msgstr "錯誤處理" + +#: src/SUMMARY.md +#, fuzzy +msgid "Error Handling: QR Example" +msgstr "錯誤處理" + +#: src/SUMMARY.md +#, fuzzy +msgid "Error Handling: PNG Example" +msgstr "錯誤處理" + +#: src/SUMMARY.md +msgid "Using CXX in Chromium" +msgstr "在 Chromium 中使用 CXX" + +#: src/SUMMARY.md src/chromium/adding-third-party-crates.md +msgid "Adding Third Party Crates" +msgstr "新增第三方 Crate" + +#: src/SUMMARY.md +msgid "Configuring Cargo.toml" +msgstr "設定 Cargo.toml" + +#: src/SUMMARY.md +#: src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +msgid "Configuring `gnrt_config.toml`" +msgstr "設定 `gnrt_config.toml`" + +#: src/SUMMARY.md src/chromium/adding-third-party-crates/downloading-crates.md +msgid "Downloading Crates" +msgstr "下載 Crate" + +#: src/SUMMARY.md +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "Generating `gn` Build Rules" +msgstr "產生 `gn` 建構規則" + +#: src/SUMMARY.md src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Resolving Problems" +msgstr "解決問題" + +#: src/SUMMARY.md +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md +msgid "Build Scripts Which Generate Code" +msgstr "建構用於產生程式碼的指令碼" + +#: src/SUMMARY.md +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +msgid "Build Scripts Which Build C++ or Take Arbitrary Actions" +msgstr "建構用於建立 C++ 或執行任意動作的指令碼" + +#: src/SUMMARY.md +#: src/chromium/adding-third-party-crates/depending-on-a-crate.md +msgid "Depending on a Crate" +msgstr "使用 Crate" + +#: src/SUMMARY.md +msgid "Reviews and Audits" +msgstr "程式庫審查和稽核" + +#: src/SUMMARY.md +msgid "Checking into Chromium Source Code" +msgstr "提交為 Chromium 原始碼" + +#: src/SUMMARY.md src/chromium/adding-third-party-crates/keeping-up-to-date.md +msgid "Keeping Crates Up to Date" +msgstr "保持 Crate 為最新版本" + +#: src/SUMMARY.md +msgid "Bringing It Together - Exercise" +msgstr "融會貫通 - 練習題" + +#: src/SUMMARY.md src/exercises/chromium/solutions.md +#, fuzzy +msgid "Exercise Solutions" +msgstr "練習題的參考答案" + +#: src/SUMMARY.md msgid "Bare Metal: Morning" msgstr "裸機開發:上午" -#: src/SUMMARY.md:219 -msgid "no_std" -msgstr "no_std" +#: src/SUMMARY.md src/bare-metal/no_std.md +msgid "`no_std`" +msgstr "`no_std`" -#: src/SUMMARY.md:220 +#: src/SUMMARY.md msgid "A Minimal Example" -msgstr "最小限度範例" +msgstr "最小限度的範例" -#: src/SUMMARY.md:221 -msgid "alloc" -msgstr "alloc" +#: src/SUMMARY.md src/bare-metal/no_std.md src/bare-metal/alloc.md +msgid "`alloc`" +msgstr "`alloc`" -#: src/SUMMARY.md:222 src/bare-metal/microcontrollers.md:1 +#: src/SUMMARY.md src/bare-metal/microcontrollers.md msgid "Microcontrollers" msgstr "微控制器" -#: src/SUMMARY.md:223 src/bare-metal/microcontrollers/mmio.md:1 +#: src/SUMMARY.md src/bare-metal/microcontrollers/mmio.md msgid "Raw MMIO" msgstr "原始 MMIO" -#: src/SUMMARY.md:224 +#: src/SUMMARY.md msgid "PACs" msgstr "PAC" -#: src/SUMMARY.md:225 +#: src/SUMMARY.md msgid "HAL Crates" msgstr "HAL Crates" -#: src/SUMMARY.md:226 +#: src/SUMMARY.md msgid "Board Support Crates" msgstr "開發板支援 Crate" -#: src/SUMMARY.md:227 +#: src/SUMMARY.md msgid "The Type State Pattern" msgstr "型別狀態模式" -#: src/SUMMARY.md:228 -msgid "embedded-hal" -msgstr "embedded-hal" +#: src/SUMMARY.md src/bare-metal/microcontrollers/embedded-hal.md +msgid "`embedded-hal`" +msgstr "`embedded-hal`" -#: src/SUMMARY.md:229 -msgid "probe-rs, cargo-embed" +#: src/SUMMARY.md src/bare-metal/microcontrollers/probe-rs.md +#, fuzzy +msgid "`probe-rs` and `cargo-embed`" msgstr "probe-rs、cargo-embed" -#: src/SUMMARY.md:230 src/bare-metal/microcontrollers/debugging.md:1 +#: src/SUMMARY.md src/bare-metal/microcontrollers/debugging.md msgid "Debugging" msgstr "偵錯" -#: src/SUMMARY.md:231 src/SUMMARY.md:251 +#: src/SUMMARY.md msgid "Other Projects" msgstr "其他專案" -#: src/SUMMARY.md:233 src/exercises/bare-metal/compass.md:1 -#: src/exercises/bare-metal/solutions-morning.md:3 +#: src/SUMMARY.md src/exercises/bare-metal/compass.md +#: src/exercises/bare-metal/solutions-morning.md msgid "Compass" msgstr "指南針" -#: src/SUMMARY.md:235 -msgid "Bare Metal: Afternoon" -msgstr "裸機開發:下午" - -#: src/SUMMARY.md:237 -msgid "Application Processors" -msgstr "應用程式處理器" - -#: src/SUMMARY.md:239 -msgid "Inline Assembly" -msgstr "行內組語" - -#: src/SUMMARY.md:240 -msgid "MMIO" -msgstr "MMIO" - -#: src/SUMMARY.md:241 -msgid "Let's Write a UART Driver" -msgstr "編寫 UART 驅動程式" - -#: src/SUMMARY.md:242 -msgid "More Traits" -msgstr "其他特徵" - -#: src/SUMMARY.md:243 -msgid "A Better UART Driver" -msgstr "經改良的 UART 驅動程式" - -#: src/SUMMARY.md:244 src/bare-metal/aps/better-uart/bitflags.md:1 -msgid "Bitflags" -msgstr "Bitflags" - -#: src/SUMMARY.md:245 -msgid "Multiple Registers" -msgstr "多個暫存器" - -#: src/SUMMARY.md:246 src/bare-metal/aps/better-uart/driver.md:1 -msgid "Driver" -msgstr "驅動程式" - -#: src/SUMMARY.md:247 src/SUMMARY.md:249 -msgid "Using It" -msgstr "開始使用" - -#: src/SUMMARY.md:252 -msgid "Useful Crates" -msgstr "實用的 Crate" - -#: src/SUMMARY.md:253 -msgid "zerocopy" -msgstr "zerocopy" - -#: src/SUMMARY.md:254 -msgid "aarch64-paging" -msgstr "aarch64-paging" - -#: src/SUMMARY.md:255 -msgid "buddy_system_allocator" -msgstr "buddy_system_allocator" - -#: src/SUMMARY.md:256 -msgid "tinyvec" -msgstr "tinyvec" - -#: src/SUMMARY.md:257 -msgid "spin" -msgstr "旋轉" - -#: src/SUMMARY.md:259 src/bare-metal/android/vmbase.md:1 -msgid "vmbase" -msgstr "vmbase" - -#: src/SUMMARY.md:261 -msgid "RTC Driver" -msgstr "RTC 驅動程式" - -#: src/SUMMARY.md:264 -msgid "Concurrency: Morning" -msgstr "並行:上午" - -#: src/SUMMARY.md:260 src/concurrency/threads.md:1 -msgid "Threads" -msgstr "執行緒" - -#: src/SUMMARY.md:261 src/concurrency/scoped-threads.md:1 -msgid "Scoped Threads" -msgstr "限定範圍執行緒" - -#: src/SUMMARY.md:262 src/concurrency/channels.md:1 -msgid "Channels" -msgstr "通道" - -#: src/SUMMARY.md:263 src/concurrency/channels/unbounded.md:1 -msgid "Unbounded Channels" -msgstr "無界限的通道" - -#: src/SUMMARY.md:264 src/concurrency/channels/bounded.md:1 -msgid "Bounded Channels" -msgstr "有界限的通道" - -#: src/SUMMARY.md:274 -msgid "Send and Sync" -msgstr "Send 和 Sync" - -#: src/SUMMARY.md:274 -msgid "Send" -msgstr "Send" - -#: src/SUMMARY.md:274 -msgid "Sync" -msgstr "Sync" - -#: src/SUMMARY.md:268 src/concurrency/send-sync/examples.md:1 -msgid "Examples" -msgstr "範例" - -#: src/SUMMARY.md:269 src/concurrency/shared_state.md:1 -msgid "Shared State" -msgstr "共享狀態" - -#: src/SUMMARY.md:279 -msgid "Arc" -msgstr "Arc" - -#: src/SUMMARY.md:280 -msgid "Mutex" -msgstr "Mutex" - -#: src/SUMMARY.md:283 src/SUMMARY.md:304 -#: src/exercises/concurrency/dining-philosophers.md:1 -#: src/exercises/concurrency/solutions-morning.md:3 -msgid "Dining Philosophers" -msgstr "哲學家就餐問題" - -#: src/SUMMARY.md:284 src/exercises/concurrency/link-checker.md:1 -msgid "Multi-threaded Link Checker" -msgstr "多執行緒連結檢查器" - -#: src/SUMMARY.md:286 -msgid "Concurrency: Afternoon" -msgstr "並行:下午" - -#: src/SUMMARY.md:288 -msgid "Async Basics" -msgstr "Async 基本概念" - -#: src/SUMMARY.md:289 -msgid "async/await" -msgstr "async/await" - -#: src/SUMMARY.md:290 src/async/futures.md:1 -msgid "Futures" -msgstr "Futures" - -#: src/SUMMARY.md:291 src/async/runtimes.md:1 -msgid "Runtimes" -msgstr "Runtimes" - -#: src/SUMMARY.md:292 src/async/runtimes/tokio.md:1 -msgid "Tokio" -msgstr "Tokio" - -#: src/SUMMARY.md:293 src/exercises/concurrency/link-checker.md:126 -#: src/async/tasks.md:1 src/exercises/concurrency/chat-app.md:143 -msgid "Tasks" -msgstr "工作" - -#: src/SUMMARY.md:294 src/async/channels.md:1 -msgid "Async Channels" -msgstr "非同步管道" - -#: src/SUMMARY.md:296 src/async/control-flow/join.md:1 -msgid "Join" -msgstr "加入" - -#: src/SUMMARY.md:297 src/async/control-flow/select.md:1 -msgid "Select" -msgstr "選取" - -#: src/SUMMARY.md:298 -msgid "Pitfalls" -msgstr "陷阱" - -#: src/SUMMARY.md:299 -msgid "Blocking the Executor" -msgstr "阻占執行器" - -#: src/SUMMARY.md:300 src/async/pitfalls/pin.md:1 -msgid "Pin" -msgstr "釘選" - -#: src/SUMMARY.md:301 src/async/pitfalls/async-traits.md:1 -msgid "Async Traits" -msgstr "非同步特徵" - -#: src/SUMMARY.md:305 src/exercises/concurrency/chat-app.md:1 -#: src/exercises/concurrency/solutions-afternoon.md:119 -msgid "Broadcast Chat Application" -msgstr "廣播聊天應用程式" - -#: src/SUMMARY.md:308 -msgid "Final Words" -msgstr "結語" - -#: src/SUMMARY.md:312 src/thanks.md:1 -msgid "Thanks!" -msgstr "謝謝!" - -#: src/SUMMARY.md:313 -msgid "Other Resources" -msgstr "其他資源" - -#: src/SUMMARY.md:304 src/credits.md:1 -msgid "Credits" -msgstr "出處清單" - -#: src/SUMMARY.md:317 src/exercises/solutions.md:1 +#: src/SUMMARY.md msgid "Solutions" msgstr "解決方案" -#: src/SUMMARY.md:322 -msgid "Day 1 Morning" -msgstr "第 1 天上午" +#: src/SUMMARY.md +msgid "Bare Metal: Afternoon" +msgstr "裸機開發:下午" -#: src/SUMMARY.md:323 -msgid "Day 1 Afternoon" -msgstr "第 1 天下午" +#: src/SUMMARY.md +msgid "Application Processors" +msgstr "應用程式處理器" -#: src/SUMMARY.md:324 -msgid "Day 2 Morning" -msgstr "第 2 天上午" +#: src/SUMMARY.md src/bare-metal/aps/entry-point.md +msgid "Getting Ready to Rust" +msgstr "準備使用 Rust" -#: src/SUMMARY.md:325 -msgid "Day 2 Afternoon" -msgstr "第 2 天下午" +#: src/SUMMARY.md +msgid "Inline Assembly" +msgstr "行內組語" -#: src/SUMMARY.md:326 -msgid "Day 3 Morning" -msgstr "第 3 天上午" +#: src/SUMMARY.md +msgid "MMIO" +msgstr "MMIO" -#: src/SUMMARY.md:327 -msgid "Day 3 Afternoon" -msgstr "第 3 天下午" +#: src/SUMMARY.md +msgid "Let's Write a UART Driver" +msgstr "編寫 UART 驅動程式" -#: src/SUMMARY.md:328 -msgid "Bare Metal Rust Morning" -msgstr "Rust 裸機開發:上午" +#: src/SUMMARY.md +msgid "More Traits" +msgstr "其他特徵" -#: src/SUMMARY.md:329 src/exercises/bare-metal/solutions-afternoon.md:1 -msgid "Bare Metal Rust Afternoon" -msgstr "Rust 裸機開發:下午" +#: src/SUMMARY.md +msgid "A Better UART Driver" +msgstr "經改良的 UART 驅動程式" -#: src/SUMMARY.md:330 -msgid "Concurrency Morning" +#: src/SUMMARY.md src/bare-metal/aps/better-uart/bitflags.md +msgid "Bitflags" +msgstr "Bitflags" + +#: src/SUMMARY.md +msgid "Multiple Registers" +msgstr "多個暫存器" + +#: src/SUMMARY.md src/bare-metal/aps/better-uart/driver.md +msgid "Driver" +msgstr "驅動程式" + +#: src/SUMMARY.md +msgid "Using It" +msgstr "開始使用" + +#: src/SUMMARY.md src/bare-metal/aps/exceptions.md +msgid "Exceptions" +msgstr "例外狀況" + +#: src/SUMMARY.md +msgid "Useful Crates" +msgstr "實用的 Crate" + +#: src/SUMMARY.md src/bare-metal/useful-crates/zerocopy.md +msgid "`zerocopy`" +msgstr "`zerocopy`" + +#: src/SUMMARY.md src/bare-metal/useful-crates/aarch64-paging.md +msgid "`aarch64-paging`" +msgstr "`aarch64-paging`" + +#: src/SUMMARY.md src/bare-metal/useful-crates/buddy_system_allocator.md +msgid "`buddy_system_allocator`" +msgstr "`buddy_system_allocator`" + +#: src/SUMMARY.md src/bare-metal/useful-crates/tinyvec.md +msgid "`tinyvec`" +msgstr "`tinyvec`" + +#: src/SUMMARY.md src/bare-metal/useful-crates/spin.md +msgid "`spin`" +msgstr "`spin`" + +#: src/SUMMARY.md +msgid "`vmbase`" +msgstr "`vmbase`" + +#: src/SUMMARY.md +msgid "RTC Driver" +msgstr "RTC 驅動程式" + +#: src/SUMMARY.md +msgid "Concurrency: Morning" msgstr "並行:上午" -#: src/SUMMARY.md:331 -msgid "Concurrency Afternoon" +#: src/SUMMARY.md src/concurrency/threads.md +msgid "Threads" +msgstr "執行緒" + +#: src/SUMMARY.md src/concurrency/scoped-threads.md +msgid "Scoped Threads" +msgstr "限定範圍執行緒" + +#: src/SUMMARY.md src/concurrency/channels.md +msgid "Channels" +msgstr "通道" + +#: src/SUMMARY.md src/concurrency/channels/unbounded.md +msgid "Unbounded Channels" +msgstr "無界限的通道" + +#: src/SUMMARY.md src/concurrency/channels/bounded.md +msgid "Bounded Channels" +msgstr "有界限的通道" + +#: src/SUMMARY.md src/concurrency/send-sync.md +msgid "`Send` and `Sync`" +msgstr "`Send` 和 `Sync`" + +#: src/SUMMARY.md src/concurrency/send-sync/send.md +msgid "`Send`" +msgstr "`Send`" + +#: src/SUMMARY.md src/concurrency/send-sync/sync.md +msgid "`Sync`" +msgstr "`Sync`" + +#: src/SUMMARY.md src/concurrency/send-sync/examples.md +msgid "Examples" +msgstr "範例" + +#: src/SUMMARY.md src/concurrency/shared_state.md +msgid "Shared State" +msgstr "共享狀態" + +#: src/SUMMARY.md src/concurrency/shared_state/arc.md +msgid "`Arc`" +msgstr "`Arc`" + +#: src/SUMMARY.md src/concurrency/shared_state/mutex.md +msgid "`Mutex`" +msgstr "`Mutex`" + +#: src/SUMMARY.md src/memory-management/review.md +#: src/error-handling/try-conversions.md +#: src/concurrency/shared_state/example.md +msgid "Example" +msgstr "範例" + +#: src/SUMMARY.md src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +msgid "Dining Philosophers" +msgstr "哲學家就餐問題" + +#: src/SUMMARY.md src/exercises/concurrency/link-checker.md +msgid "Multi-threaded Link Checker" +msgstr "多執行緒連結檢查器" + +#: src/SUMMARY.md +msgid "Concurrency: Afternoon" msgstr "並行:下午" -#: src/welcome.md:3 -msgid "" -"[![Build workflow](https://img.shields.io/github/actions/workflow/status/" -"google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" -"google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain)" -msgstr "" +#: src/SUMMARY.md +msgid "Async Basics" +msgstr "Async 基本概念" -#: src/welcome.md:3 -msgid "Build workflow" -msgstr "" +#: src/SUMMARY.md src/async/async-await.md +msgid "`async`/`await`" +msgstr "`async`/`await`" -#: src/welcome.md:3 +#: src/SUMMARY.md src/async/futures.md +msgid "Futures" +msgstr "Futures" + +#: src/SUMMARY.md src/async/runtimes.md +msgid "Runtimes" +msgstr "Runtimes" + +#: src/SUMMARY.md src/async/runtimes/tokio.md +msgid "Tokio" +msgstr "Tokio" + +#: src/SUMMARY.md src/exercises/concurrency/link-checker.md src/async/tasks.md +#: src/exercises/concurrency/chat-app.md +msgid "Tasks" +msgstr "工作" + +#: src/SUMMARY.md src/async/channels.md +msgid "Async Channels" +msgstr "非同步管道" + +#: src/SUMMARY.md +msgid "Control Flow" +msgstr "控制流程" + +#: src/SUMMARY.md src/async/control-flow/join.md +msgid "Join" +msgstr "加入" + +#: src/SUMMARY.md src/async/control-flow/select.md +msgid "Select" +msgstr "選取" + +#: src/SUMMARY.md +msgid "Pitfalls" +msgstr "陷阱" + +#: src/SUMMARY.md +msgid "Blocking the Executor" +msgstr "阻占執行器" + +#: src/SUMMARY.md src/async/pitfalls/pin.md +msgid "`Pin`" +msgstr "`Pin`" + +#: src/SUMMARY.md src/async/pitfalls/async-traits.md +msgid "Async Traits" +msgstr "非同步特徵" + +#: src/SUMMARY.md src/async/pitfalls/cancellation.md +#, fuzzy +msgid "Cancellation" +msgstr "安裝" + +#: src/SUMMARY.md src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "Broadcast Chat Application" +msgstr "廣播聊天應用程式" + +#: src/SUMMARY.md +msgid "Final Words" +msgstr "結語" + +#: src/SUMMARY.md src/thanks.md +msgid "Thanks!" +msgstr "謝謝!" + +#: src/SUMMARY.md src/glossary.md +msgid "Glossary" +msgstr "詞彙解釋" + +#: src/SUMMARY.md +msgid "Other Resources" +msgstr "其他資源" + +#: src/SUMMARY.md src/credits.md +msgid "Credits" +msgstr "出處清單" + +#: src/index.md msgid "" "[![Build workflow](https://img.shields.io/github/actions/workflow/status/" "google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" "google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain) [!" "[GitHub contributors](https://img.shields.io/github/contributors/google/" "comprehensive-rust?style=flat-square)](https://github.com/google/" -"comprehensive-rust/graphs/contributors)" -msgstr "" - -#: src/welcome.md:4 -msgid "GitHub contributors" -msgstr "" - -#: src/welcome.md:4 -msgid "" -"[![GitHub contributors](https://img.shields.io/github/contributors/google/" -"comprehensive-rust?style=flat-square)](https://github.com/google/" "comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields." "io/github/stars/google/comprehensive-rust?style=flat-square)](https://github." "com/google/comprehensive-rust/stargazers)" msgstr "" +"[![Build workflow](https://img.shields.io/github/actions/workflow/status/" +"google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" +"google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain) [!" +"[GitHub contributors](https://img.shields.io/github/contributors/google/" +"comprehensive-rust?style=flat-square)](https://github.com/google/" +"comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields." +"io/github/stars/google/comprehensive-rust?style=flat-square)](https://github." +"com/google/comprehensive-rust/stargazers)" -#: src/welcome.md:5 -msgid "GitHub stars" -msgstr "" - -#: src/welcome.md:5 +#: src/index.md msgid "" -"[![GitHub stars](https://img.shields.io/github/stars/google/comprehensive-" -"rust?style=flat-square)](https://github.com/google/comprehensive-rust/" -"stargazers)" +"This is a free Rust course developed by the Android team at Google. The " +"course covers the full spectrum of Rust, from basic syntax to advanced " +"topics like generics and error handling." msgstr "" +"這個免費的 Rust 課程是由 Google 的 Android 團隊負責開發。本課程涵蓋 Rust 的全" +"部內容,從基礎語法到進階主題 (泛型和錯誤處理等),應有盡有。" -#: src/welcome.md:7 +#: src/index.md msgid "" -"This is a three day Rust course developed by the Android team. The course " -"covers the full spectrum of Rust, from basic syntax to advanced topics like " -"generics and error handling. It also includes Android-specific content on " -"the last day." +"The latest version of the course can be found at . If you are reading somewhere else, please check there " +"for updates." +msgstr "" +"如需最新版課程,請造訪 。假如您" +"是在其他網址閱讀課程資料,別忘了查看這個連結的內容是否有更新。" + +#: src/index.md +msgid "The course is also available [as a PDF](comprehensive-rust.pdf)." msgstr "" -#: src/index.md:15 +#: src/index.md msgid "" "The goal of the course is to teach you Rust. We assume you don't know " "anything about Rust and hope to:" msgstr "" "本課程旨在教授 Rust 的知識。我們會假設您是從零開始學習 Rust,希望能夠:" -#: src/index.md:18 +#: src/index.md msgid "Give you a comprehensive understanding of the Rust syntax and language." msgstr "讓您對 Rust 語法和語言有全面的認識。" -#: src/index.md:19 +#: src/index.md msgid "Enable you to modify existing programs and write new programs in Rust." msgstr "讓您學會在 Rust 中修改現有程式及編寫新程式。" -#: src/index.md:20 +#: src/index.md msgid "Show you common Rust idioms." msgstr "向您介紹常見的 Rust 慣用語法。" -#: src/welcome.md:18 -msgid "" -"The first three days show you the fundamentals of Rust. Following this, " -"you're invited to dive into one or more specialized topics:" -msgstr "" +#: src/index.md +#, fuzzy +msgid "We call the first four course days Rust Fundamentals." +msgstr "我們將前三天的課程稱為「Rust 基礎知識」。" -#: src/index.md:26 +#: src/index.md +msgid "" +"Building on this, you're invited to dive into one or more specialized topics:" +msgstr "在此基礎上,我們將誠摯邀請您深入探討一或多個專題:" + +#: src/index.md msgid "" "[Android](android.md): a half-day course on using Rust for Android platform " "development (AOSP). This includes interoperability with C, C++, and Java." @@ -1095,37 +1374,51 @@ msgstr "" "[Android](android.md):這是半天的課程,會說明如何針對 Android 平台開發作業 " "(Android 開放原始碼計畫) 使用 Rust,並介紹與 C、C++ 和 Java 的互通性。" -#: src/welcome.md:23 +#: src/index.md +#, fuzzy msgid "" -"[Bare-metal](bare-metal.md): a full day class on using Rust for bare-metal " +"[Chromium](chromium.md): a half-day course on using Rust within Chromium " +"based browsers. This includes interoperability with C++ and how to include " +"third-party crates in Chromium." +msgstr "" +"[Chromium](chromium.md): 是半天的深入探索課程,會說明如何在 Chromium 瀏覽器" +"中使用 Rust。這包括在 Chromium 的 `gn` 建構系統中使用 Rust,以提供與第三方程" +"式庫 (「Crate」) 和 C++ 的互通性。" + +#: src/index.md +msgid "" +"[Bare-metal](bare-metal.md): a whole-day class on using Rust for bare-metal " "(embedded) development. Both microcontrollers and application processors are " "covered." msgstr "" "[Bare-metal](bare-metal.md):這是半天的課程,會說明如何使用 Rust 在 bare-" "metal (嵌入式系統) 上台開發。課程內容包含微控制器和處理器。" -#: src/welcome.md:26 +#: src/index.md msgid "" -"[Concurrency](concurrency.md): a full day class on concurrency in Rust. We " +"[Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We " "cover both classical concurrency (preemptively scheduling using threads and " "mutexes) and async/await concurrency (cooperative multitasking using " "futures)." msgstr "" +"[並行](concurrency.md):這個全天課程著重於 Rust 中的並行問題。我們將探討傳統" +"並行 (使用執行緒和互斥鎖進行先占式排程) 以及 async/await 並行 (使用 future 進" +"行合作多工處理)。" -#: src/index.md:37 +#: src/index.md msgid "Non-Goals" msgstr "非課程目標" -#: src/index.md:39 +#: src/index.md msgid "" "Rust is a large language and we won't be able to cover all of it in a few " "days. Some non-goals of this course are:" msgstr "" "Rust 是大型的程式語言,無法在幾天內就介紹完畢。因此,本課程不包含下列內容:" -#: src/welcome.md:37 +#: src/index.md msgid "" -"Learn how to develop macros, please see [Chapter 19.5 in the Rust Book]" +"Learning how to develop macros: please see [Chapter 19.5 in the Rust Book]" "(https://doc.rust-lang.org/book/ch19-06-macros.html) and [Rust by Example]" "(https://doc.rust-lang.org/rust-by-example/macros.html) instead." msgstr "" @@ -1133,24 +1426,28 @@ msgstr "" "rust-lang.org/book/ch19-06-macros.html) 和 [Rust by Example](https://doc." "rust-lang.org/rust-by-example/macros.html)." -#: src/index.md:46 +#: src/index.md msgid "Assumptions" msgstr "課程要求" -#: src/welcome.md:43 +#: src/index.md msgid "" "The course assumes that you already know how to program. Rust is a " -"statically typed language and we will sometimes make comparisons with C and " +"statically-typed language and we will sometimes make comparisons with C and " "C++ to better explain or contrast the Rust approach." msgstr "" +"本課程假設您已瞭解如何設計程式。Rust 是一種靜態的程式設計類型,我們有時會將其" +"與 C 和 C++ 比較,以便進一步解釋或凸顯 Rust 做法上的差別。" -#: src/welcome.md:47 +#: src/index.md msgid "" -"If you know how to program in a dynamically typed language such as Python or " +"If you know how to program in a dynamically-typed language such as Python or " "JavaScript, then you will be able to follow along just fine too." msgstr "" +"如果您知道如何以 Python 或 JavaScript 等動態程式語言編寫程式,也很適合跟著我" +"們學習 Rust。" -#: src/index.md:57 +#: src/index.md msgid "" "This is an example of a _speaker note_. We will use these to add additional " "information to the slides. This could be key points which the instructor " @@ -1159,21 +1456,34 @@ msgstr "" "這是「演講者備忘稿」的範例。我們會透過這些備忘稿補充投影片中未提到的資訊。這" "可能包括老師應提及的重點,以及課堂上典型問題的解答。" -#: src/running-the-course.md:3 src/running-the-course/course-structure.md:3 +#: src/running-the-course.md src/running-the-course/course-structure.md msgid "This page is for the course instructor." msgstr "本頁面的適用對象為課程講師。" -#: src/running-the-course.md:5 +#: src/running-the-course.md msgid "" "Here is a bit of background information about how we've been running the " "course internally at Google." msgstr "以下提供一些背景資訊,說明 Google 內部近期採用的授課方式。" -#: src/running-the-course.md:8 +#: src/running-the-course.md +#, fuzzy +msgid "" +"We typically run classes from 9:00 am to 4:00 pm, with a 1 hour lunch break " +"in the middle. This leaves 3 hours for the morning class and 3 hours for the " +"afternoon class. Both sessions contain multiple breaks and time for students " +"to work on exercises." +msgstr "" +"我們一般會從上午 10 點上課到下午 4 點,中間 1 小時午休。也就是說,上下午課程" +"各為 2.5 小時。請注意,這只是建議的上課時間:您也可以將上午的課程訂為 3 小" +"時,讓學員有更多時間練習。延長課程時間的缺點是,學員上了整整 6 小時的課,到了" +"下午可能會非常疲倦。" + +#: src/running-the-course.md msgid "Before you run the course, you will want to:" msgstr "在講授課程前,建議您注意下列事項:" -#: src/running-the-course.md:10 +#: src/running-the-course.md msgid "" "Make yourself familiar with the course material. We've included speaker " "notes to help highlight the key points (please help us by contributing more " @@ -1186,18 +1496,19 @@ msgstr "" "「Speaker Notes」旁小箭頭的連結)。如此一來,您就能在課堂上分享簡潔的螢幕畫" "面。" -#: src/running-the-course.md:16 +#: src/running-the-course.md +#, fuzzy msgid "" -"Decide on the dates. Since the course takes at least three full days, we " -"recommend that you schedule the days over two weeks. Course participants " -"have said that they find it helpful to have a gap in the course since it " -"helps them process all the information we give them." +"Decide on the dates. Since the course takes four days, we recommend that you " +"schedule the days over two weeks. Course participants have said that they " +"find it helpful to have a gap in the course since it helps them process all " +"the information we give them." msgstr "" "請決定授課日期。由於課程長度至少為三個整天,建議您將授課日分散安排在兩週內。" "課程參與者曾表示,如果課程中間有間隔,可協助他們消化我們提供的所有資訊,對學" "習效果有助益。" -#: src/running-the-course.md:21 +#: src/running-the-course.md msgid "" "Find a room large enough for your in-person participants. We recommend a " "class size of 15-25 people. That's small enough that people are comfortable " @@ -1212,7 +1523,7 @@ msgstr "" "師和學員使用:您們都會需要能坐著使用筆電。 講師尤其會需要現場編寫許多程式碼," "因此使用講台可能會造成不便。" -#: src/running-the-course.md:29 +#: src/running-the-course.md msgid "" "On the day of your course, show up to the room a little early to set things " "up. We recommend presenting directly using `mdbook serve` running on your " @@ -1226,7 +1537,7 @@ msgstr "" "rust#building))。這可確保提供最佳效能,不會在您切換頁面時發生延遲。使用筆電也" "可讓您修正自己或課程參與者發現的錯字。" -#: src/running-the-course.md:35 +#: src/running-the-course.md msgid "" "Let people solve the exercises by themselves or in small groups. We " "typically spend 30-45 minutes on exercises in the morning and in the " @@ -1241,13 +1552,13 @@ msgstr "" "助。如果發現多位學員遇到相同問題,請向全班說明該問題,並提供解決方式:例如示" "範如何在標準程式庫 (The Rust Standard Library) 找到相關資訊。" -#: src/running-the-course.md:43 +#: src/running-the-course.md msgid "" "That is all, good luck running the course! We hope it will be as much fun " "for you as it has been for us!" msgstr "以上為所有注意事項,祝您授課順利,並和我們一樣樂在其中!" -#: src/running-the-course.md:46 +#: src/running-the-course.md msgid "" "Please [provide feedback](https://github.com/google/comprehensive-rust/" "discussions/86) afterwards so that we can keep improving the course. We " @@ -1260,44 +1571,179 @@ msgstr "" "改善的地方。也歡迎您的學生[提供意見回饋](https://github.com/google/" "comprehensive-rust/discussions/100)!" -#: src/running-the-course/course-structure.md:5 -msgid "The course is fast paced and covers a lot of ground:" -msgstr "本課程步調快速,涵蓋許多層面:" +#: src/running-the-course/course-structure.md +msgid "Rust Fundamentals" +msgstr "Rust 基礎知識" -#: src/running-the-course/course-structure.md:7 -msgid "Day 1: Basic Rust, ownership and the borrow checker." +#: src/running-the-course/course-structure.md +#, fuzzy +msgid "" +"The first four days make up [Rust Fundamentals](../welcome-day-1.md). The " +"days are fast paced and we cover a lot of ground!" msgstr "" -"第 1 天:Rust 基礎知識、擁有權 (ownership) 與借用檢查器 (borrow checker)。" +"我們會在前三天介紹 [Rust 基礎知識](../welcome-day-1.md)。這幾天的步調會稍快," +"因為要探討許多層面:" -#: src/running-the-course/course-structure.md:8 -msgid "Day 2: Compound data types, pattern matching, the standard library." -msgstr "第 2 天:複合資料型別、模式比對 (pattern matching)、標準程式庫。" +#: src/running-the-course/course-structure.md +#, fuzzy +msgid "Course schedule:" +msgstr "課程架構" -#: src/running-the-course/course-structure.md:9 -msgid "Day 3: Traits and generics, error handling, testing, unsafe Rust." -msgstr "" -"第 3 天:特徵 (traits) 與泛型 (generics)、錯誤處理、測試、不安全的 Rust。" +#: src/running-the-course/course-structure.md +msgid "Day 1 Morning (2 hours and 10 minutes, including breaks)" +msgstr "第 1 天上午 (2 小時 10 分鐘,含休息)" -#: src/running-the-course/course-structure.md:11 +#: src/running-the-course/course-structure.md +msgid "[Welcome](../welcome-day-1.md) (5 minutes)" +msgstr "[歡迎](../welcome-day-1.md) (5 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Hello, World](../hello-world.md) (15 minutes)" +msgstr "[Hello, World](../hello-world.md) (15 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Types and Values](../types-and-values.md) (45 minutes)" +msgstr "[型別和值](../types-and-values.md) (5 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Control Flow Basics](../control-flow-basics.md) (40 minutes)" +msgstr "[基本的控制流程概念](../control-flow-basics.md) (40 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 1 Afternoon (2 hours and 15 minutes, including breaks)" +msgstr "第 1 天下午 (2 小時 15 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Tuples and Arrays](../tuples-and-arrays.md) (35 minutes)" +msgstr "[元組和陣列](../tuples-and-arrays.md) (35 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[References](../references.md) (35 minutes)" +msgstr "[參照](../references.md) (35 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[User-Defined Types](../user-defined-types.md) (50 minutes)" +msgstr "[使用者定義的型別](../user-defined-types.md) (50 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 2 Morning (2 hours and 50 minutes, including breaks)" +msgstr "第 2 天上午 (2 小時 50 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Welcome](../welcome-day-2.md) (3 minutes)" +msgstr "[歡迎](../welcome-day-2.md) (3 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Pattern Matching](../pattern-matching.md) (1 hour)" +msgstr "[模式比對](../pattern-matching.md) (1 小時)" + +#: src/running-the-course/course-structure.md +msgid "[Methods and Traits](../methods-and-traits.md) (45 minutes)" +msgstr "[方法 (methods) 和特徵 (traits)](../methods-and-traits.md) (45 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Generics](../generics.md) (40 minutes)" +msgstr "[泛型 (generics)](../generics.md) (40 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 2 Afternoon (3 hours and 10 minutes, including breaks)" +msgstr "第 2 天下午 (3 小時 10 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Standard Library Types](../std-types.md) (1 hour and 20 minutes)" +msgstr "[標準程式庫型別](../std-types.md) (1 小時 20 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Standard Library Traits](../std-traits.md) (1 hour and 40 minutes)" +msgstr "[標準程式庫特徵](../std-traits.md) (1 小時 40 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 3 Morning (2 hours and 20 minutes, including breaks)" +msgstr "第 3 天上午 (2 小時 20 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Welcome](../welcome-day-3.md) (3 minutes)" +msgstr "[歡迎](../welcome-day-3.md) (3 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Memory Management](../memory-management.md) (1 hour)" +msgstr "[記憶體管理](../memory-management.md) (1 小時)" + +#: src/running-the-course/course-structure.md +msgid "[Smart Pointers](../smart-pointers.md) (55 minutes)" +msgstr "[智慧指標](../smart-pointers.md) (55 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 3 Afternoon (2 hours and 10 minutes, including breaks)" +msgstr "第 3 天下午 (2 小時 10 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Borrowing](../borrowing.md) (50 minutes)" +msgstr "[借用](../borrowing.md) (50 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "" +"[Slices and Lifetimes](../slices-and-lifetimes.md) (1 hour and 10 minutes)" +msgstr "[切片 (slice) 和生命週期](../slices-and-lifetimes.md) (1 小時 10 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 4 Morning (2 hours and 40 minutes, including breaks)" +msgstr "第 4 天上午 (2 小時 40 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Welcome](../welcome-day-4.md) (3 minutes)" +msgstr "[歡迎](../welcome-day-4.md) (3 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Iterators](../iterators.md) (45 minutes)" +msgstr "[疊代器](../iterators.md) (45 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Modules](../modules.md) (40 minutes)" +msgstr "[模組](../modules.md) (40 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Testing](../testing.md) (45 minutes)" +msgstr "[測試](../testing.md) (45 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "Day 4 Afternoon (2 hours and 10 minutes, including breaks)" +msgstr "第 4 天下午 (2 小時 10 分鐘,含休息)" + +#: src/running-the-course/course-structure.md +msgid "[Error Handling](../error-handling.md) (55 minutes)" +msgstr "[錯誤處理](../error-handling.md) (55 分鐘)" + +#: src/running-the-course/course-structure.md +msgid "[Unsafe Rust](../unsafe-rust.md) (1 hour and 5 minutes)" +msgstr "[不安全的 Rust](../unsafe-rust.md) (1 小時 5 分鐘)" + +#: src/running-the-course/course-structure.md msgid "Deep Dives" msgstr "深入探索" -#: src/running-the-course/course-structure.md:13 +#: src/running-the-course/course-structure.md +#, fuzzy msgid "" -"In addition to the 3-day class on Rust Fundamentals, we cover some more " +"In addition to the 4-day class on Rust Fundamentals, we cover some more " "specialized topics:" msgstr "除了為期 3 天的 Rust 基礎知識課程,我們也涵蓋更多專門主題:" -#: src/running-the-course/course-structure.md:18 +#: src/running-the-course/course-structure.md +#, fuzzy +msgid "Rust in Android" +msgstr "Android 中的 Rust" + +#: src/running-the-course/course-structure.md msgid "" -"The [Android Deep Dive](../android.md) is a half-day course on using Rust " -"for Android platform development. This includes interoperability with C, C+" -"+, and Java." +"The [Rust in Android](../android.md) deep dive is a half-day course on using " +"Rust for Android platform development. This includes interoperability with " +"C, C++, and Java." msgstr "" -"[Android 深入探索](../android.md)是半天的課程,會說明如何針對 Android 平台開" +"[Android 中的 Rust](../android.md)是半天的課程,會說明如何針對 Android 平台開" "發作業使用 Rust,以及與 C、C++ 和 Java 的互通性。" -#: src/running-the-course/course-structure.md:22 +#: src/running-the-course/course-structure.md msgid "" "You will need an [AOSP checkout](https://source.android.com/docs/setup/" "download/downloading). Make a checkout of the [course repository](https://" @@ -1305,13 +1751,13 @@ msgid "" "android/` directory into the root of your AOSP checkout. This will ensure " "that the Android build system sees the `Android.bp` files in `src/android/`." msgstr "" -"您會需要進行 [Android 開放原始碼計畫檢查](https://source.android.com/docs/" -"setup/download/downloading)。請檢查[課程存放區](https://github.com/google/" -"comprehensive-rust)上相同的機器,並將 `src/android/` 目錄移至 Android 開放原" -"始碼計畫檢查的根層級。這可確保 Android 建構系統在 `src/android/` 中看到 " -"`Android.bp` 檔案。" +"您會需要檢出 (checkout) [AOSP (Android 開放原始碼專案)](https://source." +"android.com/docs/setup/download/downloading)。請檢查[課程存放區](https://" +"comprehensive-rust)上相同的機器,並將 `src/android/` 目錄移至檢出的 AOSP 根目" +"錄下。這可確保 Android 建構系統能夠在 `src/android/` 中看到 `Android.bp` 的檔" +"案。" -#: src/running-the-course/course-structure.md:27 +#: src/running-the-course/course-structure.md msgid "" "Ensure that `adb sync` works with your emulator or real device and pre-build " "all Android examples using `src/android/build_all.sh`. Read the script to " @@ -1321,20 +1767,48 @@ msgstr "" "build_all.sh` 預先建構所有 Android 範例。請閱讀指令碼,瞭解指令碼執行的指令," "並確保可以手動執行指令。" -#: src/running-the-course/course-structure.md:34 -msgid "Bare-Metal" +#: src/running-the-course/course-structure.md +#, fuzzy +msgid "Rust in Chromium" +msgstr "在 Chromium 中的 Rust" + +#: src/running-the-course/course-structure.md +msgid "" +"The [Rust in Chromium](../chromium.md) deep dive is a half-day course on " +"using Rust as part of the Chromium browser. It includes using Rust in " +"Chromium's `gn` build system, bringing in third-party libraries (\"crates\") " +"and C++ interoperability." +msgstr "" +"[Chromium 中的 Rust](../chromium.md) 是半天的深入探索課程,會說明如何在 " +"Chromium 瀏覽器中使用 Rust。這包括在 Chromium 的 `gn` 建構系統中使用 Rust,以" +"提供與第三方程式庫 (「Crate」) 和 C++ 的互通性。" + +#: src/running-the-course/course-structure.md +msgid "" +"You will need to be able to build Chromium --- a debug, component build is " +"[recommended](../chromium/setup.md) for speed but any build will work. " +"Ensure that you can run the Chromium browser that you've built." +msgstr "" +"您需具備 Chromium 的建構知識。我們[建議](../chromium/setup.md)使用偵錯元件版" +"本來加快執行速度,但其他版本也適用。請確保您能夠執行所建構的 Chromium 瀏覽" +"器。" + +#: src/running-the-course/course-structure.md +#, fuzzy +msgid "Bare-Metal Rust" msgstr "裸機" -#: src/running-the-course/course-structure.md:36 +#: src/running-the-course/course-structure.md +#, fuzzy msgid "" -"The [Bare-Metal Deep Dive](../bare-metal.md): a full day class on using Rust " -"for bare-metal (embedded) development. Both microcontrollers and application " -"processors are covered." +"The [Bare-Metal Rust](../bare-metal.md) deep dive is a full day class on " +"using Rust for bare-metal (embedded) development. Both microcontrollers and " +"application processors are covered." msgstr "" "[裸機深入探索](../bare-metal.md)是一整天的課程,會說明如何使用 Rust 進行裸機 " "(嵌入式) 開發作業,也會介紹微控制器和應用程式處理器。" -#: src/running-the-course/course-structure.md:40 +#: src/running-the-course/course-structure.md msgid "" "For the microcontroller part, you will need to buy the [BBC micro:bit]" "(https://microbit.org/) v2 development board ahead of time. Everybody will " @@ -1345,19 +1819,21 @@ msgstr "" "開發板。此外,所有人都需要按照[歡迎頁面](../bare-metal.md)上的指示安裝多種套" "件。" -#: src/running-the-course/course-structure.md:45 -msgid "Concurrency" -msgstr "並行" +#: src/running-the-course/course-structure.md +#, fuzzy +msgid "Concurrency in Rust" +msgstr "歡迎使用 Rust 的並行程式設計" -#: src/running-the-course/course-structure.md:47 +#: src/running-the-course/course-structure.md +#, fuzzy msgid "" -"The [Concurrency Deep Dive](../concurrency.md) is a full day class on " -"classical as well as `async`/`await` concurrency." +"The [Concurrency in Rust](../concurrency.md) deep dive is a full day class " +"on classical as well as `async`/`await` concurrency." msgstr "" "[並行深入探索](../concurrency.md)是一整天的課程,會說明傳統並行與 `async`/" "`await` 並行。" -#: src/running-the-course/course-structure.md:50 +#: src/running-the-course/course-structure.md msgid "" "You will need a fresh crate set up and the dependencies downloaded and ready " "to go. You can then copy/paste the examples into `src/main.rs` to experiment " @@ -1366,110 +1842,148 @@ msgstr "" "您會需要設定新的 Crate,然後下載並準備執行依附元件。接著就能將範例複製貼上至 " "`src/main.rs`,使用這些範例進行實驗:" -#: src/running-the-course/course-structure.md:54 -msgid "" -"```shell\n" -"cargo init concurrency\n" -"cd concurrency\n" -"cargo add tokio --features full\n" -"cargo run\n" -"```" -msgstr "" -"```shell\n" -"cargo init concurrency\n" -"cd concurrency\n" -"cargo add tokio --features full\n" -"cargo run\n" -"```" - -#: src/running-the-course/course-structure.md:61 +#: src/running-the-course/course-structure.md msgid "Format" msgstr "形式" -#: src/running-the-course/course-structure.md:63 +#: src/running-the-course/course-structure.md msgid "" "The course is meant to be very interactive and we recommend letting the " "questions drive the exploration of Rust!" msgstr "本課程極具互動性,因此建議您根據各項疑問,帶領學員瞭解 Rust!" -#: src/running-the-course/keyboard-shortcuts.md:3 +#: src/running-the-course/keyboard-shortcuts.md msgid "There are several useful keyboard shortcuts in mdBook:" msgstr "以下為 mdBook 中實用的鍵盤快速鍵:" -#: src/running-the-course/keyboard-shortcuts.md:5 +#: src/running-the-course/keyboard-shortcuts.md msgid "Arrow-Left" msgstr "向左鍵" -#: src/running-the-course/keyboard-shortcuts.md:5 +#: src/running-the-course/keyboard-shortcuts.md msgid ": Navigate to the previous page." msgstr ":前往上一頁。" -#: src/running-the-course/keyboard-shortcuts.md:6 +#: src/running-the-course/keyboard-shortcuts.md msgid "Arrow-Right" msgstr "向右鍵" -#: src/running-the-course/keyboard-shortcuts.md:6 +#: src/running-the-course/keyboard-shortcuts.md msgid ": Navigate to the next page." msgstr ":前往下一頁。" -#: src/running-the-course/keyboard-shortcuts.md:7 src/cargo/code-samples.md:19 +#: src/running-the-course/keyboard-shortcuts.md src/cargo/code-samples.md msgid "Ctrl + Enter" msgstr "Ctrl + Enter" -#: src/running-the-course/keyboard-shortcuts.md:7 +#: src/running-the-course/keyboard-shortcuts.md msgid ": Execute the code sample that has focus." msgstr ":執行具有焦點的程式碼範例。" -#: src/running-the-course/keyboard-shortcuts.md:8 +#: src/running-the-course/keyboard-shortcuts.md msgid "s" msgstr "s" -#: src/running-the-course/keyboard-shortcuts.md:8 +#: src/running-the-course/keyboard-shortcuts.md msgid ": Activate the search bar." msgstr ":啟用搜尋列。" -#: src/running-the-course/translations.md:3 +#: src/running-the-course/translations.md msgid "" "The course has been translated into other languages by a set of wonderful " "volunteers:" msgstr "本課程已由一群優秀的志工翻譯成其他語言:" -#: src/running-the-course/translations.md:6 +#: src/running-the-course/translations.md +#, fuzzy msgid "" "[Brazilian Portuguese](https://google.github.io/comprehensive-rust/pt-BR/) " -"by [@rastringer](https://github.com/rastringer) and [@hugojacob](https://" -"github.com/hugojacob)." +"by [@rastringer](https://github.com/rastringer), [@hugojacob](https://github." +"com/hugojacob), [@joaovicmendes](https://github.com/joaovicmendes), and " +"[@henrif75](https://github.com/henrif75)." msgstr "" "\\[巴西葡萄牙文\\]\\][pt-BR](https://google.github.io/comprehensive-rust/pt-" "BR/)譯者:[@rastringer](https://github.com/rastringer) 和 [@hugojacob]" "(https://github.com/hugojacob)。" -#: src/running-the-course/translations.md:7 +#: src/running-the-course/translations.md +msgid "" +"[Chinese (Simplified)](https://google.github.io/comprehensive-rust/zh-CN/) " +"by [@suetfei](https://github.com/suetfei), [@wnghl](https://github.com/" +"wnghl), [@anlunx](https://github.com/anlunx), [@kongy](https://github.com/" +"kongy), [@noahdragon](https://github.com/noahdragon), [@superwhd](https://" +"github.com/superwhd), [@SketchK](https://github.com/SketchK), and [@nodmp]" +"(https://github.com/nodmp)." +msgstr "" +"[中文 (簡體)](https://google.github.io/comprehensive-rust/zh-CN/)譯者:" +"[@suetfei](https://github.com/suetfei)、[@wnghl](https://github.com/wnghl)、" +"[@anlunx](https://github.com/anlunx)、[@kongy](https://github.com/kongy)、" +"[@noahdragon](https://github.com/noahdragon、[@superwhd](https://github.com/" +"superwhd)、[@SketchK](https://github.com/SketchK) 和 [@nodmp](https://" +"github) .com/nodmp)。" + +#: src/running-the-course/translations.md +#, fuzzy +msgid "" +"[Chinese (Traditional)](https://google.github.io/comprehensive-rust/zh-TW/) " +"by [@hueich](https://github.com/hueich), [@victorhsieh](https://github.com/" +"victorhsieh), [@mingyc](https://github.com/mingyc), [@kuanhungchen](https://" +"github.com/kuanhungchen), and [@johnathan79717](https://github.com/" +"johnathan79717)." +msgstr "" +"[中文 (簡體)](https://google.github.io/comprehensive-rust/zh-CN/)譯者:" +"[@suetfei](https://github.com/suetfei)、[@wnghl](https://github.com/wnghl)、" +"[@anlunx](https://github.com/anlunx)、[@kongy](https://github.com/kongy)、" +"[@noahdragon](https://github.com/noahdragon、[@superwhd](https://github.com/" +"superwhd)、[@SketchK](https://github.com/SketchK) 和 [@nodmp](https://" +"github) .com/nodmp)。" + +#: src/running-the-course/translations.md +#, fuzzy msgid "" "[Korean](https://google.github.io/comprehensive-rust/ko/) by [@keispace]" -"(https://github.com/keispace), [@jiyongp](https://github.com/jiyongp) and " -"[@jooyunghan](https://github.com/jooyunghan)." +"(https://github.com/keispace), [@jiyongp](https://github.com/jiyongp), " +"[@jooyunghan](https://github.com/jooyunghan), and [@namhyung](https://github." +"com/namhyung)." msgstr "" "[韓文](https://google.github.io/comprehensive-rust/ko/)譯者:[@keispace]" "(https://github.com/keispace)、[@jiyongp](https://github.com/jiyongp) 和 " "[@jooyunghan](https://github.com/jooyunghan)。" -#: src/running-the-course/translations.md:9 +#: src/running-the-course/translations.md +#, fuzzy +msgid "" +"[Spanish](https://google.github.io/comprehensive-rust/es/) by [@deavid]" +"(https://github.com/deavid)." +msgstr "" +"[法文](https://google.github.io/comprehensive-rust/fr/)譯者:[@KookaS]" +"(https://github.com/KookaS) 和 [@vcaen](https://github.com/vcaen)。" + +#: src/running-the-course/translations.md msgid "" "Use the language picker in the top-right corner to switch between languages." msgstr "使用右上角的語言選單即可切換語言。" -#: src/running-the-course/translations.md:11 +#: src/running-the-course/translations.md msgid "Incomplete Translations" msgstr "不完整翻譯" -#: src/running-the-course/translations.md:13 +#: src/running-the-course/translations.md msgid "" "There is a large number of in-progress translations. We link to the most " "recently updated translations:" msgstr "目前有許多正在翻譯的語言版本。以下連結為最近更新的翻譯:" -#: src/running-the-course/translations.md:16 +#: src/running-the-course/translations.md +#, fuzzy +msgid "" +"[Bengali](https://google.github.io/comprehensive-rust/bn/) by [@raselmandol]" +"(https://github.com/raselmandol)." +msgstr "" +"[德文](https://google.github.io/comprehensive-rust/de/)譯者:[@Throvn]" +"(https://github.com/Throvn)和 [@ronaldfw](https://github.com/ronaldfw)。" + +#: src/running-the-course/translations.md msgid "" "[French](https://google.github.io/comprehensive-rust/fr/) by [@KookaS]" "(https://github.com/KookaS) and [@vcaen](https://github.com/vcaen)." @@ -1477,7 +1991,7 @@ msgstr "" "[法文](https://google.github.io/comprehensive-rust/fr/)譯者:[@KookaS]" "(https://github.com/KookaS) 和 [@vcaen](https://github.com/vcaen)。" -#: src/running-the-course/translations.md:17 +#: src/running-the-course/translations.md msgid "" "[German](https://google.github.io/comprehensive-rust/de/) by [@Throvn]" "(https://github.com/Throvn) and [@ronaldfw](https://github.com/ronaldfw)." @@ -1485,7 +1999,7 @@ msgstr "" "[德文](https://google.github.io/comprehensive-rust/de/)譯者:[@Throvn]" "(https://github.com/Throvn)和 [@ronaldfw](https://github.com/ronaldfw)。" -#: src/running-the-course/translations.md:18 +#: src/running-the-course/translations.md msgid "" "[Japanese](https://google.github.io/comprehensive-rust/ja/) by [@CoinEZ-JPN]" "(https://github.com/CoinEZ) and [@momotaro1105](https://github.com/" @@ -1494,7 +2008,17 @@ msgstr "" "[日文](https://google.github.io/comprehensive-rust/ja/)譯者:\\[@\\] CoinEZ-" "JPN\\] 和 [@momotaro1105](https://github.com/momotaro1105)。" -#: src/running-the-course/translations.md:20 +#: src/running-the-course/translations.md +#, fuzzy +msgid "" +"[Italian](https://google.github.io/comprehensive-rust/it/) by " +"[@henrythebuilder](https://github.com/henrythebuilder) and [@detro](https://" +"github.com/detro)." +msgstr "" +"[德文](https://google.github.io/comprehensive-rust/de/)譯者:[@Throvn]" +"(https://github.com/Throvn)和 [@ronaldfw](https://github.com/ronaldfw)。" + +#: src/running-the-course/translations.md msgid "" "If you want to help with this effort, please see [our instructions](https://" "github.com/google/comprehensive-rust/blob/main/TRANSLATIONS.md) for how to " @@ -1504,7 +2028,7 @@ msgstr "" "如果想協助翻譯,請參閱\\[操作說明\\],瞭解如何開始翻譯。譯者可以在\\[問題追蹤" "工具\\]上討論及統整翻譯。" -#: src/cargo.md:3 +#: src/cargo.md msgid "" "When you start reading about Rust, you will soon meet [Cargo](https://doc." "rust-lang.org/cargo/), the standard tool used in the Rust ecosystem to build " @@ -1516,111 +2040,84 @@ msgstr "" "cargo/),這是在 Rust 生態系統中使用的標準工具,用於建構及執行 Rust 應用程式。" "以下簡要介紹 Cargo,以及如何在更廣大的生態系統和本訓練課程中運用 Cargo。" -#: src/cargo.md:8 +#: src/cargo.md msgid "Installation" msgstr "安裝" -#: src/cargo.md:10 -msgid "Rustup (Recommended)" -msgstr "Rustup (建議)" +#: src/cargo.md +msgid "**Please follow the instructions on .**" +msgstr "**請按照 中的指示操作。**" -#: src/cargo.md:12 +#: src/cargo.md +#, fuzzy msgid "" -"You can follow the instructions to install cargo and rust compiler, among " -"other standard ecosystem tools with the [rustup](https://rust-analyzer." -"github.io/) tool, which is maintained by the Rust Foundation." -msgstr "" -"您可以按照指示安裝 Cargo 和 Rust 編譯器,並運用 Rust Foundation 維護的 " -"[rustup](https://rust-analyzer.github.io/) 工具安裝其他標準生態系統工具。" - -#: src/cargo.md:14 -msgid "" -"Along with cargo and rustc, Rustup will install itself as a command line " -"utility that you can use to install/switch toolchains, setup cross " -"compilation, etc." +"This will give you the Cargo build tool (`cargo`) and the Rust compiler " +"(`rustc`). You will also get `rustup`, a command line utility that you can " +"use to install to different compiler versions." msgstr "" "除了安裝 Cargo 和 rustc 之外,Rustup 還會將自己安裝為指令列公用程式,方便您安" "裝/切換工具鏈、設定跨平台程式碼編譯等。" -#: src/cargo.md:16 -msgid "Package Managers" -msgstr "套件管理員" - -#: src/cargo.md:18 -msgid "Debian" -msgstr "Debian" - -#: src/cargo.md:20 +#: src/cargo.md msgid "" -"On Debian/Ubuntu, you can install Cargo, the Rust source and the [Rust " -"formatter](https://github.com/rust-lang/rustfmt) with" +"After installing Rust, you should configure your editor or IDE to work with " +"Rust. Most editors do this by talking to [rust-analyzer](https://rust-" +"analyzer.github.io/), which provides auto-completion and jump-to-definition " +"functionality for [VS Code](https://code.visualstudio.com/), [Emacs](https://" +"rust-analyzer.github.io/manual.html#emacs), [Vim/Neovim](https://rust-" +"analyzer.github.io/manual.html#vimneovim), and many others. There is also a " +"different IDE available called [RustRover](https://www.jetbrains.com/rust/)." +msgstr "" +"安裝 Rust 後,您應設定編輯器或 IDE,以便與 Rust 搭配使用。為此,大多數編輯器" +"會與 [rust-analyzer](https://rust-analyzer.github.io/) 通訊,後者提供適用於 " +"[VS Code](https://code.visualstudio.com/)、[Emacs](https://rust-analyzer." +"github.io/manual.html#emacs)、[Vim/Neovim](https://rust-analyzer.github.io/" +"manual.html#vimneovim) 等的自動完成和跳至定義功能。此外,您也可以使用稱做 " +"[RustRover](https://www.jetbrains.com/rust/) 的不同 IDE。" + +#: src/cargo.md +#, fuzzy +msgid "" +"On Debian/Ubuntu, you can also install Cargo, the Rust source and the [Rust " +"formatter](https://github.com/rust-lang/rustfmt) via `apt`. However, this " +"gets you an outdated rust version and may lead to unexpected behavior. The " +"command would be:" msgstr "" "您可以在 Debian/Ubuntu 上使用下列程式碼,安裝 Cargo、Rust 原始碼和 [Rust 格式" "設定工具](https://github.com/rust-lang/rustfmt):" -#: src/cargo.md:22 -msgid "" -"```shell\n" -"$ sudo apt install cargo rust-src rustfmt\n" -"```" -msgstr "" -"```shell\n" -"$ sudo apt install cargo rust-src rustfmt\n" -"```" - -#: src/cargo.md:26 -msgid "" -"This will allow \\[rust-analyzer\\]\\[1\\] to jump to the definitions. We " -"suggest using [VS Code](https://code.visualstudio.com/) to edit the code " -"(but any LSP compatible editor works)." -msgstr "" -"這樣一來,\\[rust-analyzer\\]\\[1\\] 就能跳至定義。建議您使用 [VS Code]" -"(https://code.visualstudio.com/) 編輯程式碼,不過任何與 LSP 相容的編輯器都能" -"運作。" - -#: src/cargo.md:29 -msgid "" -"Some folks also like to use the [JetBrains](https://www.jetbrains.com/" -"clion/) family of IDEs, which do their own analysis but have their own " -"tradeoffs. If you prefer them, you can install the [Rust Plugin](https://www." -"jetbrains.com/rust/). Please take note that as of January 2023 debugging " -"only works on the CLion version of the JetBrains IDEA suite." -msgstr "" -"有些人也偏好使用 [JetBrains](https://www.jetbrains.com/clion/) 系列的 IDE,這" -"些工具會自行分析,但也各有缺點。如果您偏好這些工具,可以安裝 [Rust 外掛程式]" -"(https://www.jetbrains.com/rust/)。請注意,自 2023 年 1 月起,偵錯功能僅適用" -"於 JetBrains IDEA 套件的 CLion 版本。" - -#: src/cargo/rust-ecosystem.md:1 +#: src/cargo/rust-ecosystem.md msgid "The Rust Ecosystem" msgstr "Rust 生態系統" -#: src/cargo/rust-ecosystem.md:3 +#: src/cargo/rust-ecosystem.md msgid "" "The Rust ecosystem consists of a number of tools, of which the main ones are:" msgstr "Rust 生態系統包含多項工具,以下列出主要工具:" -#: src/cargo/rust-ecosystem.md:5 +#: src/cargo/rust-ecosystem.md msgid "" "`rustc`: the Rust compiler which turns `.rs` files into binaries and other " "intermediate formats." msgstr "`rustc`:Rust 編譯器,可將 `.rs` 檔案轉換成二進位檔和其他中繼格式。" -#: src/cargo/rust-ecosystem.md:8 +#: src/cargo/rust-ecosystem.md +#, fuzzy msgid "" "`cargo`: the Rust dependency manager and build tool. Cargo knows how to " -"download dependencies hosted on and it will pass them to " -"`rustc` when building your project. Cargo also comes with a built-in test " -"runner which is used to execute unit tests." +"download dependencies, usually hosted on , and it will " +"pass them to `rustc` when building your project. Cargo also comes with a " +"built-in test runner which is used to execute unit tests." msgstr "" "`cargo`:Rust 依附元件管理工具和建構工具。Cargo 知道如何下載 上代管的依附元件,且會在建構您的專案時,將這些依附元件傳送至 `rustc`。" "Cargo 也提供內建測試執行元件,可用於執行單元測試。" -#: src/cargo/rust-ecosystem.md:13 +#: src/cargo/rust-ecosystem.md +#, fuzzy msgid "" "`rustup`: the Rust toolchain installer and updater. This tool is used to " -"install and update `rustc` and `cargo` when new versions of Rust is " +"install and update `rustc` and `cargo` when new versions of Rust are " "released. In addition, `rustup` can also download documentation for the " "standard library. You can have multiple versions of Rust installed at once " "and `rustup` will let you switch between them as needed." @@ -1629,18 +2126,14 @@ msgstr "" "及更新 `rustc` 和 `cargo`。此外,`rustup` 也可以下載標準程式庫的說明文件。您" "可以一次安裝多個 Rust 版本,並視需要使用 `rustup` 切換版本。" -#: src/cargo/rust-ecosystem.md:21 src/hello-world.md:25 -#: src/hello-world/small-example.md:27 src/why-rust/runtime.md:10 -#: src/why-rust/modern.md:21 src/basic-syntax/compound-types.md:30 -#: src/basic-syntax/references.md:23 -#: src/pattern-matching/destructuring-enums.md:35 -#: src/error-handling/try-operator.md:48 -#: src/error-handling/converting-error-types-example.md:50 -#: src/concurrency/threads.md:30 src/async/async-await.md:25 +#: src/cargo/rust-ecosystem.md src/types-and-values/hello-world.md +#: src/references/exclusive.md src/pattern-matching/destructuring.md +#: src/memory-management/move.md src/error-handling/try.md src/android/setup.md +#: src/async/async-await.md msgid "Key points:" msgstr "重要須知:" -#: src/cargo/rust-ecosystem.md:23 +#: src/cargo/rust-ecosystem.md msgid "" "Rust has a rapid release schedule with a new release coming out every six " "weeks. New releases maintain backwards compatibility with old releases --- " @@ -1649,20 +2142,28 @@ msgstr "" "Rust 的發布時程相當緊湊,每六週就會推出新版本。新版本可與舊版本回溯相容,且會" "啟用新功能。" -#: src/cargo/rust-ecosystem.md:27 +#: src/cargo/rust-ecosystem.md msgid "" "There are three release channels: \"stable\", \"beta\", and \"nightly\"." msgstr "" "發布版本 (release channel) 分為三種:「穩定版」、「Beta 版」和「Nightly " "版」。" -#: src/cargo/rust-ecosystem.md:29 +#: src/cargo/rust-ecosystem.md msgid "" "New features are being tested on \"nightly\", \"beta\" is what becomes " "\"stable\" every six weeks." msgstr "「Nightly 版」會用於測試新功能,「Beta 版」則會每六週成為「穩定版」。" -#: src/cargo/rust-ecosystem.md:32 +#: src/cargo/rust-ecosystem.md +msgid "" +"Dependencies can also be resolved from alternative [registries](https://doc." +"rust-lang.org/cargo/reference/registries.html), git, folders, and more." +msgstr "" +"您也可以透過其他[註冊資料庫](https://doc.rust-lang.org/cargo/reference/" +"registries.html)、git、資料夾等管道解析依附元件。" + +#: src/cargo/rust-ecosystem.md msgid "" "Rust also has [editions](https://doc.rust-lang.org/edition-guide/): the " "current edition is Rust 2021. Previous editions were Rust 2015 and Rust 2018." @@ -1670,13 +2171,13 @@ msgstr "" "Rust 還具有\\[版本\\] (edition):目前版本為 Rust 2021。先前版本為 Rust 2015 " "和 Rust 2018。" -#: src/cargo/rust-ecosystem.md:35 +#: src/cargo/rust-ecosystem.md msgid "" "The editions are allowed to make backwards incompatible changes to the " "language." msgstr "這些版本可針對語言進行回溯不相容的變更。" -#: src/cargo/rust-ecosystem.md:38 +#: src/cargo/rust-ecosystem.md msgid "" "To prevent breaking code, editions are opt-in: you select the edition for " "your crate via the `Cargo.toml` file." @@ -1684,52 +2185,53 @@ msgstr "" "為避免破壞程式碼,版本皆為自行選擇採用:您可以透過 `Cargo.toml` 檔案選擇所需" "版本。" -#: src/cargo/rust-ecosystem.md:41 +#: src/cargo/rust-ecosystem.md msgid "" "To avoid splitting the ecosystem, Rust compilers can mix code written for " "different editions." msgstr "為避免分割生態系統,Rust 編譯器可混合寫給不同版本的程式碼。" -#: src/cargo/rust-ecosystem.md:44 +#: src/cargo/rust-ecosystem.md msgid "" "Mention that it is quite rare to ever use the compiler directly not through " "`cargo` (most users never do)." msgstr "請說明很少會略過 `cargo` 直接使用編譯器,大部分使用者都不會這麼做。" -#: src/cargo/rust-ecosystem.md:46 +#: src/cargo/rust-ecosystem.md +#, fuzzy msgid "" "It might be worth alluding that Cargo itself is an extremely powerful and " -"comprehensive tool. It is capable of many advanced features including but " -"not limited to: " +"comprehensive tool. It is capable of many advanced features including but " +"not limited to:" msgstr "" "可以考慮暗示 Cargo 本身是極其強大且功能全面的工具,具有許多進階功能,包括但不" "限於:" -#: src/cargo/rust-ecosystem.md:47 +#: src/cargo/rust-ecosystem.md msgid "Project/package structure" msgstr "專案/套件結構" -#: src/cargo/rust-ecosystem.md:48 +#: src/cargo/rust-ecosystem.md msgid "[workspaces](https://doc.rust-lang.org/cargo/reference/workspaces.html)" msgstr "\\[工作區\\]" -#: src/cargo/rust-ecosystem.md:49 +#: src/cargo/rust-ecosystem.md msgid "Dev Dependencies and Runtime Dependency management/caching" msgstr "開發人員依附元件和執行階段依附元件管理/快取" -#: src/cargo/rust-ecosystem.md:50 +#: src/cargo/rust-ecosystem.md msgid "" "[build scripting](https://doc.rust-lang.org/cargo/reference/build-scripts." "html)" msgstr "\\[建構指令碼\\]" -#: src/cargo/rust-ecosystem.md:51 +#: src/cargo/rust-ecosystem.md msgid "" "[global installation](https://doc.rust-lang.org/cargo/commands/cargo-install." "html)" msgstr "\\[全域安裝\\]" -#: src/cargo/rust-ecosystem.md:52 +#: src/cargo/rust-ecosystem.md msgid "" "It is also extensible with sub command plugins as well (such as [cargo " "clippy](https://github.com/rust-lang/rust-clippy))." @@ -1737,16 +2239,16 @@ msgstr "" "此外,還可以擴充使用子指令外掛程式,例如 [cargo clippy](https://github.com/" "rust-lang/rust-clippy)" -#: src/cargo/rust-ecosystem.md:53 +#: src/cargo/rust-ecosystem.md msgid "" "Read more from the [official Cargo Book](https://doc.rust-lang.org/cargo/)" msgstr "詳情請參閱\\[官方的 Cargo 手冊\\]。" -#: src/cargo/code-samples.md:1 +#: src/cargo/code-samples.md msgid "Code Samples in This Training" msgstr "本訓練課程的程式碼範例" -#: src/cargo/code-samples.md:3 +#: src/cargo/code-samples.md msgid "" "For this training, we will mostly explore the Rust language through examples " "which can be executed through your browser. This makes the setup much easier " @@ -1755,7 +2257,7 @@ msgstr "" "在本訓練課程中,我們主要會透過範例瞭解 Rust 語言,這些範例可在瀏覽器中執行。" "這麼做可讓設定程序更輕鬆,並確保所有人獲得一致的體驗。" -#: src/cargo/code-samples.md:7 +#: src/cargo/code-samples.md msgid "" "Installing Cargo is still encouraged: it will make it easier for you to do " "the exercises. On the last day, we will do a larger exercise which shows you " @@ -1764,40 +2266,30 @@ msgstr "" "我們仍建議安裝 Cargo,方便您更輕鬆做習題。在最後一天,我們會做規模較大的習" "題,讓您瞭解如何使用依附元件,而這需要使用 Cargo。" -#: src/cargo/code-samples.md:11 +#: src/cargo/code-samples.md msgid "The code blocks in this course are fully interactive:" msgstr "本課程的程式碼區塊皆完全為互動式:" -#: src/cargo/code-samples.md:13 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"Edit me!\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"Edit me!\");\n" -"}\n" -"```" +#: src/cargo/code-samples.md src/cargo/running-locally.md +msgid "\"Edit me!\"" +msgstr "\"Edit me!\"" -#: src/cargo/code-samples.md:19 +#: src/cargo/code-samples.md msgid "You can use " msgstr "當焦點位於文字方塊時,按下 " -#: src/cargo/code-samples.md:19 +#: src/cargo/code-samples.md msgid " to execute the code when focus is in the text box." msgstr " 鍵即可執行程式碼。" -#: src/cargo/code-samples.md:24 +#: src/cargo/code-samples.md msgid "" "Most code samples are editable like shown above. A few code samples are not " "editable for various reasons:" msgstr "" "大部分程式碼範例都可供編輯,如上所示。有些程式碼範例無法編輯,原因如下:" -#: src/cargo/code-samples.md:27 +#: src/cargo/code-samples.md msgid "" "The embedded playgrounds cannot execute unit tests. Copy-paste the code and " "open it in the real Playground to demonstrate unit tests." @@ -1805,7 +2297,7 @@ msgstr "" "嵌入式遊樂場無法執行單元測試。請複製貼上程式碼,然後在實際的 Playground 中開" "啟,即可示範單元測試。" -#: src/cargo/code-samples.md:30 +#: src/cargo/code-samples.md msgid "" "The embedded playgrounds lose their state the moment you navigate away from " "the page! This is the reason that the students should solve the exercises " @@ -1814,11 +2306,11 @@ msgstr "" "當您一離開頁面,嵌入式遊樂場就會失去目前狀態!因此,學生應使用本機 Rust 安裝" "項目或透過 Playground 來做習題。" -#: src/cargo/running-locally.md:1 +#: src/cargo/running-locally.md msgid "Running Code Locally with Cargo" msgstr "使用 Cargo 在本機執行程式碼" -#: src/cargo/running-locally.md:3 +#: src/cargo/running-locally.md msgid "" "If you want to experiment with the code on your own system, then you will " "need to first install Rust. Do this by following the [instructions in the " @@ -1831,23 +2323,13 @@ msgstr "" "獲得正常運作的 `rustc` 和 `cargo`。截至本文撰寫時間,最新的 Rust 穩定版具有下" "列版本編號:" -#: src/cargo/running-locally.md:8 +#: src/cargo/running-locally.md msgid "" -"```shell\n" -"% rustc --version\n" -"rustc 1.69.0 (84c898d65 2023-04-16)\n" -"% cargo --version\n" -"cargo 1.69.0 (6e9a83356 2023-04-12)\n" -"```" -msgstr "" -"```shell\n" -"% rustc --version\n" -"rustc 1.69.0 (84c898d65 2023-04-16)\n" -"% cargo --version\n" -"cargo 1.69.0 (6e9a83356 2023-04-12)\n" -"```" +"You can use any later version too since Rust maintains backwards " +"compatibility." +msgstr "由於 Rust 保有回溯相容性,您也可以使用任何後續版本。" -#: src/cargo/running-locally.md:15 +#: src/cargo/running-locally.md msgid "" "With this in place, follow these steps to build a Rust binary from one of " "the examples in this training:" @@ -1855,53 +2337,21 @@ msgstr "" "完成上述步驟後,請按照下列步驟操作,在本訓練課程的任一範例中建構 Rust 二進位" "檔:" -#: src/cargo/running-locally.md:18 +#: src/cargo/running-locally.md msgid "Click the \"Copy to clipboard\" button on the example you want to copy." msgstr "在要複製的範例中,按一下「Copy to clipboard」按鈕。" -#: src/cargo/running-locally.md:20 +#: src/cargo/running-locally.md msgid "" "Use `cargo new exercise` to create a new `exercise/` directory for your code:" msgstr "使用 `cargo new exercise`,為程式碼建立新的 `exercise/` 目錄:" -#: src/cargo/running-locally.md:22 -msgid "" -"```shell\n" -"$ cargo new exercise\n" -" Created binary (application) `exercise` package\n" -"```" -msgstr "" -"```shell\n" -"$ cargo new exercise\n" -" Created binary (application) `exercise` package\n" -"```" - -#: src/cargo/running-locally.md:27 +#: src/cargo/running-locally.md msgid "" "Navigate into `exercise/` and use `cargo run` to build and run your binary:" msgstr "前往 `exercise/`,使用 `cargo run` 建構並執行二進位檔:" -#: src/cargo/running-locally.md:29 -msgid "" -"```shell\n" -"$ cd exercise\n" -"$ cargo run\n" -" Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" -" Finished dev [unoptimized + debuginfo] target(s) in 0.75s\n" -" Running `target/debug/exercise`\n" -"Hello, world!\n" -"```" -msgstr "" -"```shell\n" -"$ cd exercise\n" -"$ cargo run\n" -" Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" -" Finished dev [unoptimized + debuginfo] target(s) in 0.75s\n" -" Running `target/debug/exercise`\n" -"Hello, world!\n" -"```" - -#: src/cargo/running-locally.md:38 +#: src/cargo/running-locally.md msgid "" "Replace the boiler-plate code in `src/main.rs` with your own code. For " "example, using the example on the previous page, make `src/main.rs` look like" @@ -1909,43 +2359,11 @@ msgstr "" "將 `src/main.rs` 中的樣板程式碼替換為自己的程式碼。以上一頁的範例為例,替換後" "的 `src/main.rs` 會類似如下:" -#: src/cargo/running-locally.md:41 -msgid "" -"```rust\n" -"fn main() {\n" -" println!(\"Edit me!\");\n" -"}\n" -"```" -msgstr "" -"```rust\n" -"fn main() {\n" -" println!(\"Edit me!\");\n" -"}\n" -"```" - -#: src/cargo/running-locally.md:47 +#: src/cargo/running-locally.md msgid "Use `cargo run` to build and run your updated binary:" msgstr "使用 `cargo run` 建構並執行更新版二進位檔:" -#: src/cargo/running-locally.md:49 -msgid "" -"```shell\n" -"$ cargo run\n" -" Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" -" Finished dev [unoptimized + debuginfo] target(s) in 0.24s\n" -" Running `target/debug/exercise`\n" -"Edit me!\n" -"```" -msgstr "" -"```shell\n" -"$ cargo run\n" -" Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" -" Finished dev [unoptimized + debuginfo] target(s) in 0.24s\n" -" Running `target/debug/exercise`\n" -"Edit me!\n" -"```" - -#: src/cargo/running-locally.md:57 +#: src/cargo/running-locally.md msgid "" "Use `cargo check` to quickly check your project for errors, use `cargo " "build` to compile it without running it. You will find the output in `target/" @@ -1956,7 +2374,7 @@ msgstr "" "情況下編譯專案。您會在 `target/debug/` 中看到一般偵錯版本的輸出內容。使用 " "`cargo build --release`,在 `target/release/` 中產生經過最佳化的發布子版本。" -#: src/cargo/running-locally.md:62 +#: src/cargo/running-locally.md msgid "" "You can add dependencies for your project by editing `Cargo.toml`. When you " "run `cargo` commands, it will automatically download and compile missing " @@ -1965,7 +2383,7 @@ msgstr "" "只要編輯 `Cargo.toml`,即可為專案新增依附元件。執行 `cargo` 指令時,系統會自" "動下載及編譯缺少的依附元件。" -#: src/cargo/running-locally.md:70 +#: src/cargo/running-locally.md msgid "" "Try to encourage the class participants to install Cargo and use a local " "editor. It will make their life easier since they will have a normal " @@ -1974,68 +2392,108 @@ msgstr "" "建議您鼓勵課程參與者安裝 Cargo 及使用本機編輯器。這麼做能提供正常的開發環境," "降低操作難度。" -#: src/welcome-day-1.md:1 +#: src/welcome-day-1.md msgid "Welcome to Day 1" msgstr "歡迎參加第 1 天課程" -#: src/welcome-day-1.md:3 +#: src/welcome-day-1.md msgid "" -"This is the first day of Comprehensive Rust. We will cover a lot of ground " +"This is the first day of Rust Fundamentals. We will cover a lot of ground " "today:" -msgstr "" +msgstr "今天是學習 Rust 基礎知識的第一天,我們會探討許多內容:" -#: src/welcome-day-1.md:6 +#: src/welcome-day-1.md msgid "" "Basic Rust syntax: variables, scalar and compound types, enums, structs, " "references, functions, and methods." msgstr "" "基本的 Rust 語法:變數、純量和複合型別、列舉、結構體、參照、函式和方法。" -#: src/welcome-day-2.md:5 -msgid "" -"Memory management: stack vs heap, manual memory management, scope-based " -"memory management, and garbage collection." -msgstr "" -"記憶體管理:堆疊和堆積、手動管理記憶體、範圍式記憶體管理,以及垃圾收集。" +#: src/welcome-day-1.md +#, fuzzy +msgid "Types and type inference." +msgstr "型別推斷" -#: src/welcome-day-2.md:8 -msgid "" -"Ownership: move semantics, copying and cloning, borrowing, and lifetimes." -msgstr "擁有權:轉移語意、複製、借用,以及生命週期。" +#: src/welcome-day-1.md +msgid "Control flow constructs: loops, conditionals, and so on." +msgstr "控制流程結構:迴圈、條件式等。" -#: src/welcome-day-1.md:16 +#: src/welcome-day-1.md +msgid "User-defined types: structs and enums." +msgstr "使用者定義的型別:結構體和列舉。" + +#: src/welcome-day-1.md +msgid "Pattern matching: destructuring enums, structs, and arrays." +msgstr "模式配對:解構列舉、結構和陣列。" + +#: src/welcome-day-1.md src/welcome-day-2.md src/welcome-day-3.md +#: src/welcome-day-4.md +msgid "Schedule" +msgstr "課程時間表" + +#: src/welcome-day-1.md src/welcome-day-1-afternoon.md src/welcome-day-2.md +#: src/welcome-day-2-afternoon.md src/welcome-day-3.md +#: src/welcome-day-3-afternoon.md src/welcome-day-4.md +#: src/welcome-day-4-afternoon.md +msgid "In this session:" +msgstr "課程內容:" + +#: src/welcome-day-1.md +msgid "[Welcome](./welcome-day-1.md) (5 minutes)" +msgstr "[歡迎](./welcome-day-1.md) (5 分鐘)" + +#: src/welcome-day-1.md +msgid "[Hello, World](./hello-world.md) (15 minutes)" +msgstr "[Hello, World](./hello-world.md) (15 分鐘)" + +#: src/welcome-day-1.md +msgid "[Types and Values](./types-and-values.md) (45 minutes)" +msgstr "[型別和值](./types-and-values.md) (45 分鐘)" + +#: src/welcome-day-1.md +msgid "[Control Flow Basics](./control-flow-basics.md) (40 minutes)" +msgstr "[基本的控制流程概念](./control-flow-basics.md) (40 分鐘)" + +#: src/welcome-day-1.md src/welcome-day-3-afternoon.md +#: src/welcome-day-4-afternoon.md +msgid "" +"Including 10 minute breaks, this session should take about 2 hours and 10 " +"minutes" +msgstr "加上 10 分鐘的休息時間,這個課程大約需要 2 小時 10 分鐘" + +#: src/welcome-day-1.md msgid "Please remind the students that:" msgstr "請提醒學生以下事項:" -#: src/welcome-day-1.md:18 +#: src/welcome-day-1.md msgid "" "They should ask questions when they get them, don't save them to the end." msgstr "應該一有問題就提問,不要留到最後。" -#: src/welcome-day-1.md:19 +#: src/welcome-day-1.md msgid "" "The class is meant to be interactive and discussions are very much " "encouraged!" msgstr "本課程的宗旨是互動,非常鼓勵大家討論!" -#: src/welcome-day-1.md:20 +#: src/welcome-day-1.md +#, fuzzy msgid "" "As an instructor, you should try to keep the discussions relevant, i.e., " -"keep the discussions related to how Rust does things vs some other " -"language. It can be hard to find the right balance, but err on the side of " -"allowing discussions since they engage people much more than one-way " -"communication." +"keep the discussions related to how Rust does things vs some other language. " +"It can be hard to find the right balance, but err on the side of allowing " +"discussions since they engage people much more than one-way communication." msgstr "" "老師應設法讓討論不要離題,例如確保討論的主題在於比較 Rust 和其他語言的運作方" "式。要找到適當的平衡點並不容易,但我們還是寧可讓學員討論,因為這比老師單向授" "課更能引起學生興趣。" -#: src/welcome-day-1.md:24 +#: src/welcome-day-1.md msgid "" "The questions will likely mean that we talk about things ahead of the slides." msgstr "我們討論的議題,可能會超前投影片進度。" -#: src/welcome-day-1.md:25 +#: src/welcome-day-1.md msgid "" "This is perfectly okay! Repetition is an important part of learning. " "Remember that the slides are just a support and you are free to skip them as " @@ -2044,39 +2502,54 @@ msgstr "" "這完全沒問題!複習是學習的重要一環。請記得,投影片只是輔助,您可以視情況略過" "不需要的部分。" -#: src/welcome-day-1.md:29 +#: src/welcome-day-1.md msgid "" -"The idea for the first day is to show _just enough_ of Rust to be able to " -"speak about the famous borrow checker. The way Rust handles memory is a " -"major feature and we should show students this right away." +"The idea for the first day is to show the \"basic\" things in Rust that " +"should have immediate parallels in other languages. The more advanced parts " +"of Rust come on the subsequent days." msgstr "" -"第一天的規畫是說明 Rust 基礎概念,「只要剛好」能介紹到著名的借用檢查器就行" -"了。Rust 處理記憶體的方式是一大特色,我們應該立即向學生展示這一點。" +"第一天的規畫是說明 Rust 中能夠直接對應到其他語言的「基礎」概念。後續幾天則會" +"介紹更進階的部分。" -#: src/welcome-day-1.md:33 +#: src/welcome-day-1.md msgid "" "If you're teaching this in a classroom, this is a good place to go over the " -"schedule. We suggest splitting the day into two parts (following the slides):" +"schedule. Note that there is an exercise at the end of each segment, " +"followed by a break. Plan to cover the exercise solution after the break. " +"The times listed here are a suggestion in order to keep the course on " +"schedule. Feel free to be flexible and adjust as necessary!" msgstr "" -"如果您是在教室授課,就很適合參考這裡的時間表。建議您將一天分為兩部分 (根據投" -"影片安排):" +"如果您是在教室授課,就很適合參考這裡的時間表。請注意,每個主題結束後都有練" +"習,然後才是休息時間。請規劃在休息後講解練習的解決方案。此處列出的時程建議是" +"要確保課程進度。您可以視需要彈性調整!" -#: src/welcome-day-1.md:36 -msgid "Morning: 9:00 to 12:00," -msgstr "上午:9 點到 12 點" +#: src/hello-world.md src/types-and-values.md src/control-flow-basics.md +#: src/tuples-and-arrays.md src/references.md src/user-defined-types.md +#: src/pattern-matching.md src/methods-and-traits.md src/generics.md +#: src/std-types.md src/std-traits.md src/memory-management.md +#: src/smart-pointers.md src/borrowing.md src/slices-and-lifetimes.md +#: src/iterators.md src/modules.md src/testing.md src/error-handling.md +#: src/unsafe-rust.md +msgid "In this segment:" +msgstr "主題內容:" -#: src/welcome-day-1.md:37 -msgid "Afternoon: 13:00 to 16:00." -msgstr "下午:1 點到 4 點" +#: src/hello-world.md +msgid "[What is Rust?](./hello-world/what-is-rust.md) (10 minutes)" +msgstr "[什麼是 Rust?](./hello-world/what-is-rust.md) (10 分鐘)" -#: src/welcome-day-1.md:39 -msgid "" -"You can of course adjust this as necessary. Please make sure to include " -"breaks, we recommend a break every hour!" -msgstr "" -"您當然可以視需要調整這個時間表。但請務必要加入休息時段,建議每小時休息一次!" +#: src/hello-world.md +msgid "[Benefits of Rust](./hello-world/benefits.md) (3 minutes)" +msgstr "[Rust 的優點](./hello-world/benefits.md) (3 分鐘)" -#: src/welcome-day-1/what-is-rust.md:3 +#: src/hello-world.md +msgid "[Playground](./hello-world/playground.md) (2 minutes)" +msgstr "[Playground](./hello-world/playground.md) (2 分鐘)" + +#: src/hello-world.md +msgid "This segment should take about 15 minutes" +msgstr "講解這個主題大約需要 15 分鐘" + +#: src/hello-world/what-is-rust.md msgid "" "Rust is a new programming language which had its [1.0 release in 2015]" "(https://blog.rust-lang.org/2015/05/15/Rust-1.0.html):" @@ -2084,15 +2557,15 @@ msgstr "" "Rust 是一款新的程式設計語言,[在 2015 年推出 1.0 版](https://blog.rust-lang." "org/2015/05/15/Rust-1.0.html):" -#: src/welcome-day-1/what-is-rust.md:5 +#: src/hello-world/what-is-rust.md msgid "Rust is a statically compiled language in a similar role as C++" msgstr "Rust 是靜態編譯的程式語言,功能與 C++ 類似" -#: src/welcome-day-1/what-is-rust.md:6 +#: src/hello-world/what-is-rust.md msgid "`rustc` uses LLVM as its backend." msgstr "`rustc` 使用 LLVM 做為後端。" -#: src/welcome-day-1/what-is-rust.md:7 +#: src/hello-world/what-is-rust.md msgid "" "Rust supports many [platforms and architectures](https://doc.rust-lang.org/" "nightly/rustc/platform-support.html):" @@ -2100,221 +2573,162 @@ msgstr "" "Rust 支援許多[平台和架構](https://doc.rust-lang.org/nightly/rustc/platform-" "support.html):" -#: src/welcome-day-1/what-is-rust.md:9 +#: src/hello-world/what-is-rust.md msgid "x86, ARM, WebAssembly, ..." msgstr "x86、ARM、WebAssembly..." -#: src/welcome-day-1/what-is-rust.md:10 +#: src/hello-world/what-is-rust.md msgid "Linux, Mac, Windows, ..." msgstr "Linux、Mac、Windows..." -#: src/welcome-day-1/what-is-rust.md:11 +#: src/hello-world/what-is-rust.md msgid "Rust is used for a wide range of devices:" msgstr "Rust 適用於多種裝置:" -#: src/welcome-day-1/what-is-rust.md:12 +#: src/hello-world/what-is-rust.md msgid "firmware and boot loaders," msgstr "韌體和啟動載入器" -#: src/welcome-day-1/what-is-rust.md:13 +#: src/hello-world/what-is-rust.md msgid "smart displays," msgstr "智慧螢幕、" -#: src/welcome-day-1/what-is-rust.md:14 +#: src/hello-world/what-is-rust.md msgid "mobile phones," msgstr "手機、" -#: src/welcome-day-1/what-is-rust.md:15 +#: src/hello-world/what-is-rust.md msgid "desktops," msgstr "電腦、" -#: src/welcome-day-1/what-is-rust.md:16 +#: src/hello-world/what-is-rust.md msgid "servers." msgstr "伺服器。" -#: src/welcome-day-1/what-is-rust.md:21 +#: src/hello-world/what-is-rust.md msgid "Rust fits in the same area as C++:" msgstr "Rust 適合用於與 C++ 同樣的領域,且具有以下特色:" -#: src/welcome-day-1/what-is-rust.md:23 +#: src/hello-world/what-is-rust.md msgid "High flexibility." msgstr "高靈活性。" -#: src/welcome-day-1/what-is-rust.md:24 +#: src/hello-world/what-is-rust.md msgid "High level of control." msgstr "提供高度主控權。" -#: src/welcome-day-1/what-is-rust.md:25 -msgid "Can be scaled down to very constrained devices like mobile phones." -msgstr "" +#: src/hello-world/what-is-rust.md +msgid "" +"Can be scaled down to very constrained devices such as microcontrollers." +msgstr "可縮減到十分受限的裝置規模,例如微控制器。" -#: src/welcome-day-1/what-is-rust.md:26 +#: src/hello-world/what-is-rust.md msgid "Has no runtime or garbage collection." msgstr "沒有執行階段,也不使用垃圾收集機制。" -#: src/welcome-day-1/what-is-rust.md:27 +#: src/hello-world/what-is-rust.md msgid "Focuses on reliability and safety without sacrificing performance." msgstr "著重可靠性和安全性,但不犧牲效能。" -#: src/hello-world.md:3 -msgid "" -"Let us jump into the simplest possible Rust program, a classic Hello World " -"program:" -msgstr "我們直接來看看最簡單的 Rust 程式吧,也就是經典的 Hello World 程式:" - -#: src/hello-world.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"Hello 🌍!\");\n" -"}\n" -"```" -msgstr "" - -#: src/hello-world.md:12 -msgid "What you see:" -msgstr "您會看到:" - -#: src/hello-world.md:14 -msgid "Functions are introduced with `fn`." -msgstr "函式是以 `fn` 導入。" - -#: src/hello-world.md:15 -msgid "Blocks are delimited by curly braces like in C and C++." -msgstr "區塊會用大括號分隔,這跟在 C 和 C++ 一樣。" - -#: src/hello-world.md:16 -msgid "The `main` function is the entry point of the program." -msgstr "`main` 函式是程式的進入點。" - -#: src/hello-world.md:17 -msgid "Rust has hygienic macros, `println!` is an example of this." -msgstr "Rust 含有衛生巨集,例如 `println!`。" - -#: src/hello-world.md:18 -msgid "Rust strings are UTF-8 encoded and can contain any Unicode character." -msgstr "Rust 字串採用 UTF-8 編碼,可包含任何萬國碼字元。" - -#: src/hello-world.md:22 -msgid "" -"This slide tries to make the students comfortable with Rust code. They will " -"see a ton of it over the next four days so we start small with something " -"familiar." -msgstr "" - -#: src/hello-world.md:27 -msgid "" -"Rust is very much like other languages in the C/C++/Java tradition. It is " -"imperative (not functional) and it doesn't try to reinvent things unless " -"absolutely necessary." -msgstr "" - -#: src/hello-world.md:31 -msgid "Rust is modern with full support for things like Unicode." -msgstr "Rust 是現代的程式語言,可完整支援萬國碼等等。" - -#: src/hello-world.md:33 -msgid "" -"Rust uses macros for situations where you want to have a variable number of " -"arguments (no function [overloading](basic-syntax/functions-interlude.md))." -msgstr "" -"當您想使用可變數量的引數時 (亦即無任何函式[超載](basic-syntax/functions-" -"interlude.md)),可使用 Rust 的巨集。" - -#: src/hello-world.md:36 -msgid "" -"Macros being 'hygienic' means they don't accidentally capture identifiers " -"from the scope they are used in. Rust macros are actually only [partially " -"hygienic](https://veykril.github.io/tlborm/decl-macros/minutiae/hygiene." -"html)." -msgstr "" -"所謂「衛生」巨集,是指這類巨集不會誤從自身所用於的範圍內擷取 ID。Rust 巨集實" -"際上只能算是[部分衛生](https://veykril.github.io/tlborm/decl-macros/minutiae/" -"hygiene.html)的巨集。" - -#: src/hello-world/small-example.md:3 -msgid "Here is a small example program in Rust:" -msgstr "以下是使用 Rust 語言的簡短範例程式:" - -#: src/hello-world/small-example.md:5 -msgid "" -"```rust,editable\n" -"fn main() { // Program entry point\n" -" let mut x: i32 = 6; // Mutable variable binding\n" -" print!(\"{x}\"); // Macro for printing, like printf\n" -" while x != 1 { // No parenthesis around expression\n" -" if x % 2 == 0 { // Math like in other languages\n" -" x = x / 2;\n" -" } else {\n" -" x = 3 * x + 1;\n" -" }\n" -" print!(\" -> {x}\");\n" -" }\n" -" println!();\n" -"}\n" -"```" -msgstr "" - -#: src/hello-world/small-example.md:23 -msgid "" -"The code implements the Collatz conjecture: it is believed that the loop " -"will always end, but this is not yet proved. Edit the code and play with " -"different inputs." -msgstr "" -"這是「考拉茲猜想」的實作程式碼,考拉茲相信迴圈不管怎樣終會結束,但這尚未得" -"證。您可以編輯該程式碼,試著輸入不同內容。" - -#: src/hello-world/small-example.md:29 -msgid "" -"Explain that all variables are statically typed. Try removing `i32` to " -"trigger type inference. Try with `i8` instead and trigger a runtime integer " -"overflow." -msgstr "" -"解釋所有變數都是靜態的。試著移除 `i32` 來觸發型別推斷。接著嘗試改用 `i8`,並" -"觸發執行階段的整數溢位現象。" - -#: src/hello-world/small-example.md:32 -msgid "Change `let mut x` to `let x`, discuss the compiler error." -msgstr "將 `let mut x` 改為 `let x`,討論編譯器錯誤。" - -#: src/hello-world/small-example.md:34 -msgid "" -"Show how `print!` gives a compilation error if the arguments don't match the " -"format string." -msgstr "說明如果引數與格式字串不符,`print!` 會如何呈現編譯錯誤。" - -#: src/hello-world/small-example.md:37 -msgid "" -"Show how you need to use `{}` as a placeholder if you want to print an " -"expression which is more complex than just a single variable." -msgstr "說明要輸出比單一變數更複雜的運算式時,需如何使用 `{}` 做為預留位置。" - -#: src/hello-world/small-example.md:40 -msgid "" -"Show the students the standard library, show them how to search for `std::" -"fmt` which has the rules of the formatting mini-language. It's important " -"that the students become familiar with searching in the standard library." -msgstr "" -"向學生介紹標準程式庫,示範如何搜尋具有格式化迷你語言規則的 `std::fmt`。請務必" -"確保學生熟悉如何在標準程式庫中搜尋。" - -#: src/why-rust.md:3 +#: src/hello-world/benefits.md msgid "Some unique selling points of Rust:" msgstr "Rust 的幾個獨特賣點如下:" -#: src/why-rust.md:5 -msgid "Compile time memory safety." -msgstr "在編譯期間確保記憶體安全性。" +#: src/hello-world/benefits.md +msgid "" +"_Compile time memory safety_ - whole classes of memory bugs are prevented at " +"compile time" +msgstr "「編譯期的記憶體安全性」 - 在編譯期間就能避免各類記憶體錯誤" -#: src/why-rust.md:6 -msgid "Lack of undefined runtime behavior." -msgstr "沒有未定義的執行階段行為。" +#: src/hello-world/benefits.md +msgid "No uninitialized variables." +msgstr "不會產生未初始化的變數。" -#: src/why-rust.md:7 -msgid "Modern language features." -msgstr "現代的語言特色。" +#: src/hello-world/benefits.md +msgid "No double-frees." +msgstr "不會導致重複釋放記憶體。" -#: src/why-rust.md:11 +#: src/hello-world/benefits.md +msgid "No use-after-free." +msgstr "不會使用已釋放的記憶體。" + +#: src/hello-world/benefits.md +msgid "No `NULL` pointers." +msgstr "不會產生 `NULL` 指標。" + +#: src/hello-world/benefits.md +msgid "No forgotten locked mutexes." +msgstr "不會產生忘記鎖定的互斥鎖。" + +#: src/hello-world/benefits.md +msgid "No data races between threads." +msgstr "執行緒之間不會發生資料競爭。" + +#: src/hello-world/benefits.md +msgid "No iterator invalidation." +msgstr "不會發生疊代器無效的情形。" + +#: src/hello-world/benefits.md +msgid "" +"_No undefined runtime behavior_ - what a Rust statement does is never left " +"unspecified" +msgstr "" +"「不會出現未定義的執行階段行為 (undefined runtime behavior)」 - Rust 陳述式的" +"行為一律會有定義" + +#: src/hello-world/benefits.md +msgid "Array access is bounds checked." +msgstr "陣列存取行為會經過邊界檢查。" + +#: src/hello-world/benefits.md +msgid "Integer overflow is defined (panic or wrap-around)." +msgstr "整數溢位的行為是明確的 (恐慌或迴繞)。" + +#: src/hello-world/benefits.md +msgid "" +"_Modern language features_ - as expressive and ergonomic as higher-level " +"languages" +msgstr "「現代化的語言特徵」 - 具表現力且符合人因工程學的高階語言" + +#: src/hello-world/benefits.md +msgid "Enums and pattern matching." +msgstr "列舉和模式配對。" + +#: src/hello-world/benefits.md +msgid "Generics." +msgstr "泛型。" + +#: src/hello-world/benefits.md +msgid "No overhead FFI." +msgstr "沒有 FFI 負擔。" + +#: src/hello-world/benefits.md +msgid "Zero-cost abstractions." +msgstr "零成本的抽象化機制。" + +#: src/hello-world/benefits.md +msgid "Great compiler errors." +msgstr "更好的編譯錯誤描述。" + +#: src/hello-world/benefits.md +msgid "Built-in dependency manager." +msgstr "內建依附元件管理工具。" + +#: src/hello-world/benefits.md +msgid "Built-in support for testing." +msgstr "內建測試支援。" + +#: src/hello-world/benefits.md +msgid "Excellent Language Server Protocol support." +msgstr "卓越的語言伺服器通訊協定支援。" + +#: src/hello-world/benefits.md +msgid "" +"Do not spend much time here. All of these points will be covered in more " +"depth later." +msgstr "這裡不要花太多時間。這幾點稍後全都會深入介紹。" + +#: src/hello-world/benefits.md msgid "" "Make sure to ask the class which languages they have experience with. " "Depending on the answer you can highlight different features of Rust:" @@ -2322,7 +2736,7 @@ msgstr "" "請務必詢問全班同學,瞭解他們具備哪些語言的使用經驗。根據學生答覆,您可以強調" "不同的 Rust 功能:" -#: src/why-rust.md:14 +#: src/hello-world/benefits.md msgid "" "Experience with C or C++: Rust eliminates a whole class of _runtime errors_ " "via the borrow checker. You get performance like in C and C++, but you don't " @@ -2333,7 +2747,7 @@ msgstr "" "這不僅可讓您獲得像是 C 和 C++ 的效能,也不會造成記憶體安全問題。此外,您還能" "取得具備模式配對、內建依附元件管理機制等結構的新型語言。" -#: src/why-rust.md:19 +#: src/hello-world/benefits.md msgid "" "Experience with Java, Go, Python, JavaScript...: You get the same memory " "safety as in those languages, plus a similar high-level language feeling. In " @@ -2344,382 +2758,442 @@ msgstr "" "體安全性,而且還可帶來使用類似高階語言的感受。此外,您也能獲得像 C 和 C++ 一" "樣快速可預期的成效 (無垃圾收集器),以及低階硬體的存取權限 (如有需要)。" -#: src/why-rust/compile-time.md:3 -msgid "Static memory management at compile time:" -msgstr "編譯期間的靜態記憶體管理機制好處多多,包括:" - -#: src/why-rust/compile-time.md:5 -msgid "No uninitialized variables." -msgstr "不會產生未初始化的變數。" - -#: src/why-rust/compile-time.md:6 -msgid "No memory leaks (_mostly_, see notes)." -msgstr "不會造成記憶體流失 (「一般」來說是這樣,請參閱附註)。" - -#: src/why-rust/compile-time.md:7 -msgid "No double-frees." -msgstr "不會導致重複釋放記憶體。" - -#: src/why-rust/compile-time.md:8 -msgid "No use-after-free." -msgstr "不會使用已釋放的記憶體。" - -#: src/why-rust/compile-time.md:9 -msgid "No `NULL` pointers." -msgstr "不會產生 `NULL` 指標。" - -#: src/why-rust/compile-time.md:10 -msgid "No forgotten locked mutexes." -msgstr "不會產生忘記鎖定的互斥鎖。" - -#: src/why-rust/compile-time.md:11 -msgid "No data races between threads." -msgstr "執行緒之間不會發生資料競爭。" - -#: src/why-rust/compile-time.md:12 -msgid "No iterator invalidation." -msgstr "不會發生疊代器無效的情形。" - -#: src/why-rust/compile-time.md:16 +#: src/hello-world/playground.md msgid "" -"It is possible to produce memory leaks in (safe) Rust. Some examples are:" +"The [Rust Playground](https://play.rust-lang.org/) provides an easy way to " +"run short Rust programs, and is the basis for the examples and exercises in " +"this course. Try running the \"hello-world\" program it starts with. It " +"comes with a few handy features:" msgstr "" -"在 (安全的) Rust 範疇內,可能還是有機會造成記憶體流失。以下是一些例子:" +"[Rust Playground](https://play.rust-lang.org/) 支援以簡便方式執行精簡的 Rust " +"程式,也是本課程中範例和練習的基礎。不妨試著執行 Rust Playground 開頭的" +"「hello-world」程式。Playground 兼具以下幾項便利功能:" -#: src/why-rust/compile-time.md:19 +#: src/hello-world/playground.md msgid "" -"You can use [`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box." -"html#method.leak) to leak a pointer. A use of this could be to get runtime-" -"initialized and runtime-sized static variables" -msgstr "" -"您可能會使用 [`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box." -"html#method.leak),以致洩漏指標。如果您為了取得在執行階段中初始化或設定大小的" -"靜態變數,就可能發生這個情況。" +"Under \"Tools\", use the `rustfmt` option to format your code in the " +"\"standard\" way." +msgstr "在「Tools」下方點選「`rustfmt`」選項,以「標準」方式設定程式碼格式。" -#: src/why-rust/compile-time.md:21 +#: src/hello-world/playground.md msgid "" -"You can use [`std::mem::forget`](https://doc.rust-lang.org/std/mem/fn.forget." -"html) to make the compiler \"forget\" about a value (meaning the destructor " -"is never run)." +"Rust has two main \"profiles\" for generating code: Debug (extra runtime " +"checks, less optimization) and Release (fewer runtime checks, lots of " +"optimization). These are accessible under \"Debug\" at the top." msgstr "" -"您可能會透過 [`std::mem::forget`](https://doc.rust-lang.org/std/mem/fn." -"forget.html) 讓編譯器「忘記」某個值 (亦即解構函式永遠不會執行)。" +"Rust 有兩個主要的「設定檔」可產生程式碼,分別是「Debug」(加強執行階段檢查,最" +"佳化程度較低) 和「Release」(減少執行階段檢查,大規模最佳化)。這些設定檔位於頂" +"端的「Debug」下方。" -#: src/why-rust/compile-time.md:23 +#: src/hello-world/playground.md msgid "" -"You can also accidentally create a [reference cycle](https://doc.rust-lang." -"org/book/ch15-06-reference-cycles.html) with `Rc` or `Arc`." -msgstr "" -"您也可能會不小心使用 `Rc` 或 `Arc` 建立[參照循環](https://doc.rust-lang.org/" -"book/ch15-06-reference-cycles.html)。" +"If you're interested, use \"ASM\" under \"...\" to see the generated " +"assembly code." +msgstr "感興趣的話,不妨點選「...」下的「ASM」查看產生的組語程式碼。" -#: src/why-rust/compile-time.md:25 +#: src/hello-world/playground.md msgid "" -"In fact, some will consider infinitely populating a collection a memory leak " -"and Rust does not protect from those." +"As students head into the break, encourage them to open up the playground " +"and experiment a little. Encourage them to keep the tab open and try things " +"out during the rest of the course. This is particularly helpful for advanced " +"students who want to know more about Rust's optimizations or generated " +"assembly." msgstr "" -"事實上,有些人會認為無限地填充集合是一種記憶體流失,而 Rust 並不能避免這種情" -"況。" +"學員準備休息時,請鼓勵他們開啟 Playground 略微試驗一下。在剩餘的課堂時間,建" +"議他們持續開啟 Playground 分頁嘗試操作。如果學生程度較高,想進一步瞭解 Rust " +"的最佳化作業或產生的組語,就特別適合採用這個授課方式。" -#: src/why-rust/compile-time.md:28 +#: src/types-and-values.md +msgid "[Hello, World](./types-and-values/hello-world.md) (5 minutes)" +msgstr "[Hello, World](./types-and-values/hello-world.md) (5 分鐘)" + +#: src/types-and-values.md +msgid "[Variables](./types-and-values/variables.md) (5 minutes)" +msgstr "[變數](./types-and-values/variables.md) (5 分鐘)" + +#: src/types-and-values.md +msgid "[Values](./types-and-values/values.md) (5 minutes)" +msgstr "[值](./types-and-values/values.md) (5 分鐘)" + +#: src/types-and-values.md +msgid "[Arithmetic](./types-and-values/arithmetic.md) (3 minutes)" +msgstr "[算術](./types-and-values/arithmetic.md) (3 分鐘)" + +#: src/types-and-values.md +msgid "[Strings](./types-and-values/strings.md) (5 minutes)" +msgstr "[字串](./types-and-values/strings.md) (5 分鐘)" + +#: src/types-and-values.md +msgid "[Type Inference](./types-and-values/inference.md) (3 minutes)" +msgstr "[型別推斷](./types-and-values/inference.md) (3 分鐘)" + +#: src/types-and-values.md +msgid "[Exercise: Fibonacci](./types-and-values/exercise.md) (15 minutes)" +msgstr "[練習:費波那契數列](./types-and-values/exercise.md) (15 分鐘)" + +#: src/types-and-values.md src/methods-and-traits.md src/iterators.md +#: src/testing.md +msgid "This segment should take about 45 minutes" +msgstr "講解這個主題大約需要 45 分鐘" + +#: src/types-and-values/hello-world.md msgid "" -"For the purpose of this course, \"No memory leaks\" should be understood as " -"\"Pretty much no _accidental_ memory leaks\"." -msgstr "" -"因此,以本課程的宗旨來說,「沒有記憶體流失」應理解為「幾乎沒有『意外的』記憶" -"體流失」。" +"Let us jump into the simplest possible Rust program, a classic Hello World " +"program:" +msgstr "我們直接來看看最簡單的 Rust 程式吧,也就是經典的 Hello World 程式:" -#: src/why-rust/runtime.md:3 -msgid "No undefined behavior at runtime:" -msgstr "在執行階段不會產生未定義的行為,好處如下:" +#: src/types-and-values/hello-world.md +msgid "\"Hello 🌍!\"" +msgstr "\"Hello 🌍!\"" -#: src/why-rust/runtime.md:5 -msgid "Array access is bounds checked." -msgstr "陣列存取行為會經過邊界檢查。" +#: src/types-and-values/hello-world.md +msgid "What you see:" +msgstr "您會看到:" -#: src/why-rust/runtime.md:6 -msgid "Integer overflow is defined." -msgstr "" +#: src/types-and-values/hello-world.md +msgid "Functions are introduced with `fn`." +msgstr "函式是以 `fn` 導入。" -#: src/why-rust/runtime.md:12 +#: src/types-and-values/hello-world.md +msgid "Blocks are delimited by curly braces like in C and C++." +msgstr "區塊會用大括號分隔,這跟在 C 和 C++ 一樣。" + +#: src/types-and-values/hello-world.md +msgid "The `main` function is the entry point of the program." +msgstr "`main` 函式是程式的進入點。" + +#: src/types-and-values/hello-world.md +msgid "Rust has hygienic macros, `println!` is an example of this." +msgstr "Rust 含有衛生巨集,例如 `println!`。" + +#: src/types-and-values/hello-world.md +msgid "Rust strings are UTF-8 encoded and can contain any Unicode character." +msgstr "Rust 字串採用 UTF-8 編碼,可包含任何萬國碼字元。" + +#: src/types-and-values/hello-world.md msgid "" -"Integer overflow is defined via a compile-time flag. The options are either " -"a panic (a controlled crash of the program) or wrap-around semantics. By " -"default, you get panics in debug mode (`cargo build`) and wrap-around in " -"release mode (`cargo build --release`)." +"This slide tries to make the students comfortable with Rust code. They will " +"see a ton of it over the next four days so we start small with something " +"familiar." msgstr "" +"我們會藉由這張投影片,試著讓學生熟悉 Rust 程式碼。在接下來的四天裡,他們會大" +"量接觸到這些內容,所以我們得從他們熟悉的小地方著手。" -#: src/why-rust/runtime.md:18 +#: src/types-and-values/hello-world.md msgid "" -"Bounds checking cannot be disabled with a compiler flag. It can also not be " -"disabled directly with the `unsafe` keyword. However, `unsafe` allows you to " -"call functions such as `slice::get_unchecked` which does not do bounds " -"checking." +"Rust is very much like other languages in the C/C++/Java tradition. It is " +"imperative and it doesn't try to reinvent things unless absolutely necessary." msgstr "" -"您無法使用編譯器參數停用邊界檢查,也無法直接透過 `unsafe` 關鍵字停用。不過," -"您可以使用 `unsafe` 呼叫 `slice::get_unchecked` 這類不執行邊界檢查的函式。" +"Rust 與 C/C++/Java 傳統中的其他語言非常相似。它是指令式的程式語言,除非絕對必" +"要,否則不會嘗試改編任何內容。" -#: src/why-rust/modern.md:3 -msgid "Rust is built with all the experience gained in the last 40 years." -msgstr "" +#: src/types-and-values/hello-world.md +msgid "Rust is modern with full support for things like Unicode." +msgstr "Rust 是現代的程式語言,可完整支援萬國碼等等。" -#: src/why-rust/modern.md:5 -msgid "Language Features" -msgstr "語言特色" - -#: src/why-rust/modern.md:7 -msgid "Enums and pattern matching." -msgstr "列舉和模式配對。" - -#: src/why-rust/modern.md:8 -msgid "Generics." -msgstr "泛型。" - -#: src/why-rust/modern.md:9 -msgid "No overhead FFI." -msgstr "沒有 FFI 負擔。" - -#: src/why-rust/modern.md:10 -msgid "Zero-cost abstractions." -msgstr "零成本的抽象化機制。" - -#: src/why-rust/modern.md:12 -msgid "Tooling" -msgstr "工具" - -#: src/why-rust/modern.md:14 -msgid "Great compiler errors." -msgstr "更好的編譯錯誤描述。" - -#: src/why-rust/modern.md:15 -msgid "Built-in dependency manager." -msgstr "內建依附元件管理工具。" - -#: src/why-rust/modern.md:16 -msgid "Built-in support for testing." -msgstr "內建測試支援。" - -#: src/why-rust/modern.md:17 -msgid "Excellent Language Server Protocol support." -msgstr "卓越的語言伺服器通訊協定支援。" - -#: src/why-rust/modern.md:23 +#: src/types-and-values/hello-world.md +#, fuzzy msgid "" -"Zero-cost abstractions, similar to C++, means that you don't have to 'pay' " -"for higher-level programming constructs with memory or CPU. For example, " -"writing a loop using `for` should result in roughly the same low level " -"instructions as using the `.iter().fold()` construct." +"Rust uses macros for situations where you want to have a variable number of " +"arguments (no function [overloading](../control-flow-basics/functions.md))." msgstr "" -"與 C++ 類似,零成本抽象化機制是指您不必為使用記憶體或 CPU 的高階程式設計結構" -"「付費」。舉例來說,使用 `for` 編寫迴圈時,應產生與使用 `.iter().fold()` 結構" -"大致相同的低階指示。" +"當您想使用可變數量的引數時 (亦即無任何函式[超載](basic-syntax/functions-" +"interlude.md)),可使用 Rust 的巨集。" -#: src/why-rust/modern.md:28 +#: src/types-and-values/hello-world.md msgid "" -"It may be worth mentioning that Rust enums are 'Algebraic Data Types', also " -"known as 'sum types', which allow the type system to express things like " -"`Option` and `Result`." +"Macros being 'hygienic' means they don't accidentally capture identifiers " +"from the scope they are used in. Rust macros are actually only [partially " +"hygienic](https://veykril.github.io/tlborm/decl-macros/minutiae/hygiene." +"html)." msgstr "" -"值得一提的是,Rust 列舉屬於「代數資料型別」(也稱為「加總型別」),可讓型別系統" -"表達 `Option` 和 `Result` 等項目。" +"所謂「衛生」巨集,是指這類巨集不會誤從自身所用於的範圍內擷取 ID。Rust 巨集實" +"際上只能算是[部分衛生](https://veykril.github.io/tlborm/decl-macros/minutiae/" +"hygiene.html)的巨集。" -#: src/why-rust/modern.md:32 +#: src/types-and-values/hello-world.md msgid "" -"Remind people to read the errors --- many developers have gotten used to " -"ignore lengthy compiler output. The Rust compiler is significantly more " -"talkative than other compilers. It will often provide you with _actionable_ " -"feedback, ready to copy-paste into your code." +"Rust is multi-paradigm. For example, it has powerful [object-oriented " +"programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), and, " +"while it is not a functional language, it includes a range of [functional " +"concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html)." msgstr "" -"提醒使用者詳讀錯誤訊息,許多開發人員已習慣忽略冗長的編譯器輸出結果。Rust 編譯" -"器的表達能力比其他編譯器高出許多,通常都會提供「實用」的意見回饋,您可以直接" -"將其複製貼到程式碼中。" +"Rust 是多範式的語言。舉例來說,它具備強大的[物件導向程式設計功能](https://" +"doc.rust-lang.org/book/ch17-00-oop.html),雖然並非函式語言,卻涉及各式各樣的" +"[函式概念](https://doc.rust-lang.org/book/ch13-00-functional-features.html)。" -#: src/why-rust/modern.md:37 +#: src/types-and-values/variables.md +#, fuzzy msgid "" -"The Rust standard library is small compared to languages like Java, Python, " -"and Go. Rust does not come with several things you might consider standard " -"and essential:" +"Rust provides type safety via static typing. Variable bindings are made with " +"`let`:" +msgstr "Rust 可透過靜態型別確保型別安全。根據預設,變數綁定不可變動:" + +#: src/types-and-values/variables.md src/control-flow-basics/loops/for.md +#: src/control-flow-basics/blocks-and-scopes.md +msgid "\"x: {x}\"" +msgstr "\"x: {x}\"" + +#: src/types-and-values/variables.md +msgid "" +"// x = 20;\n" +" // println!(\"x: {x}\");\n" msgstr "" -"與 Java、Python 和 Go 等語言相比,Rust 標準程式庫較小。Rust 並不提供某些您可" -"能認為是標準和基本項目的內容:" +"// x = 20;\n" +" // println!(\"x: {x}\");\n" -#: src/why-rust/modern.md:41 -msgid "a random number generator, but see [rand](https://docs.rs/rand/)." -msgstr "隨機號碼產生器,請參閱 [rand](https://docs.rs/rand/)。" - -#: src/why-rust/modern.md:42 -msgid "support for SSL or TLS, but see [rusttls](https://docs.rs/rustls/)." -msgstr "SSL 或 TLS 支援,請參閱 [rusttls](https://docs.rs/rustls/)。" - -#: src/why-rust/modern.md:43 -msgid "support for JSON, but see [serde_json](https://docs.rs/serde_json/)." -msgstr "JSON 支援,請參閱 [serde_json](https://docs.rs/serde_json/)。" - -#: src/why-rust/modern.md:45 +#: src/types-and-values/variables.md msgid "" -"The reasoning behind this is that functionality in the standard library " -"cannot go away, so it has to be very stable. For the examples above, the " -"Rust community is still working on finding the best solution --- and perhaps " -"there isn't a single \"best solution\" for some of these things." +"Uncomment the `x = 20` to demonstrate that variables are immutable by " +"default. Add the `mut` keyword to allow changes." msgstr "" -"未提供此支援的原因是,標準程式庫中的功能無法移除,因此必須相當穩定。對於以上" -"範例,Rust 社群仍在努力尋找最佳解決方案,但其中某幾個例子或許並沒有單一的「最" -"佳解決方案」。" +"取消註解 `x = 20`,證明變數預設為不可變動。如要允許變更,請加入 `mut` 關鍵" +"字。" -#: src/why-rust/modern.md:50 +#: src/types-and-values/variables.md msgid "" -"Rust comes with a built-in package manager in the form of Cargo and this " -"makes it trivial to download and compile third-party crates. A consequence " -"of this is that the standard library can be smaller." +"The `i32` here is the type of the variable. This must be known at compile " +"time, but type inference (covered later) allows the programmer to omit it in " +"many cases." msgstr "" -"Rust 內建採用 Cargo 形式的套件管理工具,因此可讓您輕鬆下載及編譯第三方 " -"Crate。這樣一來,就可以縮小標準程式庫的規模。" +"這裡的 `i32` 是變數型別。這是編譯器必須在編譯期間掌握的資訊,但透過型別推斷 " +"(稍後會說明),程式設計師在許多情況下都能省略其型別宣告。" -#: src/why-rust/modern.md:54 +#: src/types-and-values/values.md msgid "" -"Discovering good third-party crates can be a problem. Sites like help with this by letting you compare health metrics for crates to " -"find a good and trusted one." -msgstr "" -"如何找到理想的第三方 Crate 可能是一大問題。但請放心, 這類網" -"站可協助您比較 Crate 的健康指標,找出優質且值得信賴的 Crate。" +"Here are some basic built-in types, and the syntax for literal values of " +"each type." +msgstr "以下列出一些基本的內建型別,以及適用於各型的字面常量的語法。" -#: src/why-rust/modern.md:58 -msgid "" -"[rust-analyzer](https://rust-analyzer.github.io/) is a well supported LSP " -"implementation used in major IDEs and text editors." -msgstr "" -"[rust-analyzer](https://rust-analyzer.github.io/) 是廣受支援的 LSP 實作項目," -"適用於主要的 IDE 和文字編輯器。" - -#: src/basic-syntax.md:3 -msgid "Much of the Rust syntax will be familiar to you from C, C++ or Java:" -msgstr "如果您有 C、C++ 或 Java 基礎,會覺得大部分的 Rust 語法都似曾相識:" - -#: src/basic-syntax.md:5 -msgid "Blocks and scopes are delimited by curly braces." -msgstr "區塊和範圍會以大括號分隔。" - -#: src/basic-syntax.md:6 -msgid "" -"Line comments are started with `//`, block comments are delimited by `/* ... " -"*/`." -msgstr "行註解以 `//` 開頭,區塊註解則以 `/* ... */` 分隔。" - -#: src/basic-syntax.md:8 -msgid "Keywords like `if` and `while` work the same." -msgstr "`if` 和 `while` 等關鍵字的功用相同。" - -#: src/basic-syntax.md:9 -msgid "Variable assignment is done with `=`, comparison is done with `==`." -msgstr "變數指派作業透過 `=` 完成,等於運算則透過 `==` 完成。" - -#: src/basic-syntax/scalar-types.md:3 src/basic-syntax/compound-types.md:3 -#: src/exercises/day-3/safe-ffi-wrapper.md:16 +#: src/types-and-values/values.md src/unsafe-rust/exercise.md msgid "Types" msgstr "類型" -#: src/basic-syntax/scalar-types.md:3 src/basic-syntax/compound-types.md:3 +#: src/types-and-values/values.md msgid "Literals" msgstr "常值" -#: src/basic-syntax/scalar-types.md:5 +#: src/types-and-values/values.md msgid "Signed integers" msgstr "帶號整數" -#: src/basic-syntax/scalar-types.md:5 +#: src/types-and-values/values.md msgid "`i8`, `i16`, `i32`, `i64`, `i128`, `isize`" msgstr "`i8`、`i16`、`i32`、`i64`、`i128`、`isize`" -#: src/basic-syntax/scalar-types.md:5 -msgid "`-10`, `0`, `1_000`, `123i64`" -msgstr "" +#: src/types-and-values/values.md +msgid "`-10`, `0`, `1_000`, `123_i64`" +msgstr "`-10`、`0`、`1_000`、`123_i64`" -#: src/basic-syntax/scalar-types.md:6 +#: src/types-and-values/values.md msgid "Unsigned integers" msgstr "非帶號整數" -#: src/basic-syntax/scalar-types.md:6 +#: src/types-and-values/values.md msgid "`u8`, `u16`, `u32`, `u64`, `u128`, `usize`" msgstr "`u8`、`u16`、`u32`、`u64`、`u128`、`usize`" -#: src/basic-syntax/scalar-types.md:6 -msgid "`0`, `123`, `10u16`" -msgstr "" +#: src/types-and-values/values.md +msgid "`0`, `123`, `10_u16`" +msgstr "`0`、`123`、`10_u16`" -#: src/basic-syntax/scalar-types.md:7 +#: src/types-and-values/values.md msgid "Floating point numbers" msgstr "浮點數" -#: src/basic-syntax/scalar-types.md:7 +#: src/types-and-values/values.md msgid "`f32`, `f64`" msgstr "`f32`、`f64`" -#: src/basic-syntax/scalar-types.md:7 -msgid "`3.14`, `-10.0e20`, `2f32`" -msgstr "" +#: src/types-and-values/values.md +msgid "`3.14`, `-10.0e20`, `2_f32`" +msgstr "`3.14`、`-10.0e20`、`2_f32`" -#: src/basic-syntax/scalar-types.md:8 -msgid "Strings" -msgstr "字串 (String)" - -#: src/basic-syntax/scalar-types.md:8 -msgid "`&str`" -msgstr "`&str`" - -#: src/basic-syntax/scalar-types.md:8 -msgid "`\"foo\"`, `\"two\\nlines\"`" -msgstr "`\"foo\"`、`\"two\\nlines\"`" - -#: src/basic-syntax/scalar-types.md:9 +#: src/types-and-values/values.md msgid "Unicode scalar values" msgstr "萬國碼純量值" -#: src/basic-syntax/scalar-types.md:9 +#: src/types-and-values/values.md src/android/aidl/types/primitives.md msgid "`char`" msgstr "`char`" -#: src/basic-syntax/scalar-types.md:9 +#: src/types-and-values/values.md msgid "`'a'`, `'α'`, `'∞'`" msgstr "`'a'`、`'α'`、`'∞'`" -#: src/basic-syntax/scalar-types.md:10 +#: src/types-and-values/values.md msgid "Booleans" msgstr "布林值" -#: src/basic-syntax/scalar-types.md:10 +#: src/types-and-values/values.md src/android/aidl/types/primitives.md msgid "`bool`" msgstr "`bool`" -#: src/basic-syntax/scalar-types.md:10 +#: src/types-and-values/values.md msgid "`true`, `false`" msgstr "`true`、`false`" -#: src/basic-syntax/scalar-types.md:12 +#: src/types-and-values/values.md msgid "The types have widths as follows:" msgstr "型別的寬度如下:" -#: src/basic-syntax/scalar-types.md:14 +#: src/types-and-values/values.md msgid "`iN`, `uN`, and `fN` are _N_ bits wide," msgstr "`iN`、`uN` 和 `fN` 的寬度為 _N_ 位元" -#: src/basic-syntax/scalar-types.md:15 +#: src/types-and-values/values.md msgid "`isize` and `usize` are the width of a pointer," msgstr "`isize` 和 `usize` 等同於指標的寬度" -#: src/basic-syntax/scalar-types.md:16 -msgid "`char` is 32 bit wide," -msgstr "" +#: src/types-and-values/values.md +msgid "`char` is 32 bits wide," +msgstr "`char` 寬度為 32 位元" -#: src/basic-syntax/scalar-types.md:17 -msgid "`bool` is 8 bit wide." -msgstr "" +#: src/types-and-values/values.md +msgid "`bool` is 8 bits wide." +msgstr "`bool` 寬度為 8 位元" -#: src/basic-syntax/scalar-types.md:21 +#: src/types-and-values/values.md msgid "There are a few syntaxes which are not shown above:" msgstr "除此之外,還有一些其他語法:" -#: src/basic-syntax/scalar-types.md:23 +#: src/types-and-values/values.md +msgid "" +"All underscores in numbers can be left out, they are for legibility only. So " +"`1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written " +"as `123i64`." +msgstr "" +"數字中的底線全都可以省略,寫出來只是為了方便閱讀。換句話說,`1_000` 可以寫成 " +"`1000` (或 `10_00`),而 `123_i64` 則可寫成 `123i64`。" + +#: src/types-and-values/arithmetic.md +msgid "\"result: {}\"" +msgstr "\"result: {}\"" + +#: src/types-and-values/arithmetic.md +msgid "" +"This is the first time we've seen a function other than `main`, but the " +"meaning should be clear: it takes three integers, and returns an integer. " +"Functions will be covered in more detail later." +msgstr "" +"這是我們第一次看到 `main` 以外的函式,但此函式的含意應該很清楚,那就是它需要" +"三個整數,且會傳回整數。我們稍後會詳細說明函式的細節。" + +#: src/types-and-values/arithmetic.md +msgid "Arithmetic is very similar to other languages, with similar precedence." +msgstr "在其他語言中,算數的方法非常相似,運算的優先順序也雷同。" + +#: src/types-and-values/arithmetic.md +msgid "" +"What about integer overflow? In C and C++ overflow of _signed_ integers is " +"actually undefined, and might do different things on different platforms or " +"compilers. In Rust, it's defined." +msgstr "" +"那麼整數溢位現象呢?在 C 和 C++ 中,「有號」整數的溢位現象實際上並未定義,而" +"且在不同的平台或編譯器上可能有不同行為。但在 Rust 中,整數溢位會經過定義。" + +#: src/types-and-values/arithmetic.md +msgid "" +"Change the `i32`'s to `i16` to see an integer overflow, which panics " +"(checked) in a debug build and wraps in a release build. There are other " +"options, such as overflowing, saturating, and carrying. These are accessed " +"with method syntax, e.g., `(a * b).saturating_add(b * c).saturating_add(c * " +"a)`." +msgstr "" +"將 `i32` 變更為 `i16`,即可查看整數溢位現象,這在偵錯版本中會造成恐慌 " +"(checked),並納入發布子版本中。此外,Rust 還提供溢位、飽和與進位等其他選項," +"可透過方法語法存取,例如 `(a * b).saturating_add(b * c).saturating_add(c * " +"a)`。" + +#: src/types-and-values/arithmetic.md +msgid "" +"In fact, the compiler will detect overflow of constant expressions, which is " +"why the example requires a separate function." +msgstr "" +"事實上,編譯器會偵測常數運算式的溢位,這也是本例中需要另一個函式的原因。" + +#: src/types-and-values/strings.md +msgid "" +"Rust has two types to represent strings, both of which will be covered in " +"more depth later. Both _always_ store UTF-8 encoded strings." +msgstr "" +"Rust 用來代表字串的型別有兩種,稍後會深入介紹。兩者「一律」都儲存 UTF-8 編碼" +"字串。" + +#: src/types-and-values/strings.md +#, fuzzy +msgid "`String` - a modifiable, owned string." +msgstr "`String` 是可變動的字串緩衝區。" + +#: src/types-and-values/strings.md +msgid "`&str` - a read-only string. String literals have this type." +msgstr "`&str` - 這是唯讀字串。字串常量會採用此型別。" + +#: src/types-and-values/strings.md +msgid "\"Greetings\"" +msgstr "\"Greetings\"" + +#: src/types-and-values/strings.md +msgid "\"🪐\"" +msgstr "\"🪐\"" + +#: src/types-and-values/strings.md +msgid "\", \"" +msgstr "\", \"" + +#: src/types-and-values/strings.md +msgid "\"final sentence: {}\"" +msgstr "\"final sentence: {}\"" + +#: src/types-and-values/strings.md +#: src/methods-and-traits/traits/associated-types.md +#: src/async/control-flow/join.md +msgid "\"{:?}\"" +msgstr "\"{:?}\"" + +#: src/types-and-values/strings.md +msgid "//println!(\"{:?}\", &sentence[12..13]);\n" +msgstr "//println!(\"{:?}\", &sentence[12..13]);\n" + +#: src/types-and-values/strings.md +msgid "" +"This slide introduces strings. Everything here will be covered in more depth " +"later, but this is enough for subsequent slides and exercises to use strings." +msgstr "" +"這張投影片用於介紹字串。我們稍後會深入介紹此處提及的所有內容,但目前這些就已" +"足夠用於後續的投影片和使用字串的練習題中。" + +#: src/types-and-values/strings.md +msgid "Invalid UTF-8 in a string is UB, and this not allowed in safe Rust." +msgstr "字串中的無效 UTF-8 屬於 UB,而安全的 Rust 環境不允許此行為。" + +#: src/types-and-values/strings.md +msgid "" +"`String` is a user-defined type with a constructor (`::new()`) and methods " +"like `s.push_str(..)`." +msgstr "" +"`String` 是使用者定義的型別,具備建構函式 (`::new()`) 和 `s.push_str(..)` 等" +"方法。" + +#: src/types-and-values/strings.md +msgid "" +"The `&` in `&str` indicates that this is a reference. We will cover " +"references later, so for now just think of `&str` as a unit meaning \"a read-" +"only string\"." +msgstr "" +"`&str` 中的 `&` 表示這是參照。我們稍後會講解何謂參照,因此現在只需將 `&str` " +"視為代表「唯讀字串」的單位就行了。" + +#: src/types-and-values/strings.md +msgid "" +"The commented-out line is indexing into the string by byte position. " +"`12..13` does not end on a character boundary, so the program panics. Adjust " +"it to a range that does, based on the error message." +msgstr "" +"被註解掉的那行程式碼會按照位元組位置建立索引到字串中。`12..13` 的結尾不是字元" +"邊界,因此程式會發生恐慌。請根據錯誤訊息,將其調整至結尾為字元邊界的範圍。" + +#: src/types-and-values/strings.md msgid "" "Raw strings allow you to create a `&str` value with escapes disabled: " "`r\"\\n\" == \"\\\\n\"`. You can embed double-quotes by using an equal " @@ -2728,994 +3202,24 @@ msgstr "" "原形字串可讓您建立停用逸出功能的 `&str` 值:`r\"\\n\" == \"\\\\n\"`。只要在引" "號兩側使用等量的 `#`,即可嵌入雙引號:" -#: src/basic-syntax/scalar-types.md:27 +#: src/types-and-values/strings.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" println!(r#\"link\"#);\n" -" println!(\"link\");\n" -"}\n" -"```" +"Using `{:?}` is a convenient way to print array/vector/struct of values for " +"debugging purposes, and it's commonly used in code." msgstr "" -#: src/basic-syntax/scalar-types.md:34 -msgid "Byte strings allow you to create a `&[u8]` value directly:" -msgstr "位元組字串可讓您直接建立 `&[u8]` 值:" - -#: src/basic-syntax/scalar-types.md:36 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"{:?}\", b\"abc\");\n" -" println!(\"{:?}\", &[97, 98, 99]);\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/compound-types.md:5 -msgid "Arrays" -msgstr "陣列" - -#: src/basic-syntax/compound-types.md:5 -msgid "`[T; N]`" -msgstr "`[T; N]`" - -#: src/basic-syntax/compound-types.md:5 -msgid "`[20, 30, 40]`, `[0; 3]`" -msgstr "`[20, 30, 40]`、`[0; 3]`" - -#: src/basic-syntax/compound-types.md:6 -msgid "Tuples" -msgstr "元組" - -#: src/basic-syntax/compound-types.md:6 -msgid "`()`, `(T,)`, `(T1, T2)`, ..." -msgstr "`()`、`(T,)`、`(T1, T2)`..." - -#: src/basic-syntax/compound-types.md:6 -msgid "`()`, `('x',)`, `('x', 1.2)`, ..." -msgstr "`()`、`('x',)`、`('x', 1.2)`..." - -#: src/basic-syntax/compound-types.md:8 -msgid "Array assignment and access:" -msgstr "陣列指派與存取:" - -#: src/basic-syntax/compound-types.md:10 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut a: [i8; 10] = [42; 10];\n" -" a[5] = 0;\n" -" println!(\"a: {:?}\", a);\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/compound-types.md:18 -msgid "Tuple assignment and access:" -msgstr "元組指派與存取:" - -#: src/basic-syntax/compound-types.md:20 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let t: (i8, bool) = (7, true);\n" -" println!(\"1st index: {}\", t.0);\n" -" println!(\"2nd index: {}\", t.1);\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/compound-types.md:32 -msgid "Arrays:" -msgstr "陣列:" - -#: src/basic-syntax/compound-types.md:34 -msgid "" -"Arrays have elements of the same type, `T`, and length, `N`, which is a " -"compile-time constant. Note that the length of the array is _part of its " -"type_, which means that `[u8; 3]` and `[u8; 4]` are considered two different " -"types." -msgstr "" - -#: src/basic-syntax/compound-types.md:38 -msgid "We can use literals to assign values to arrays." -msgstr "我們可以使用常值將值指派給陣列。" - -#: src/basic-syntax/compound-types.md:40 -msgid "" -"In the main function, the print statement asks for the debug implementation " -"with the `?` format parameter: `{}` gives the default output, `{:?}` gives " -"the debug output. We could also have used `{a}` and `{a:?}` without " -"specifying the value after the format string." -msgstr "" -"在主函式中,輸出陳述式會使用 `?` 格式參數要求偵錯實作:`{}` 提供預設輸出內" -"容,`{:?}` 則提供偵錯輸出內容。我們也可以使用 `{a}` 和 `{a:?}` 而不需指定格式" -"字串後方的值。" - -#: src/basic-syntax/compound-types.md:45 -msgid "" -"Adding `#`, eg `{a:#?}`, invokes a \"pretty printing\" format, which can be " -"easier to read." -msgstr "加入 `#` (例如 `{a:#?}`) 可叫用方便閱讀的「美化排版」格式。" - -#: src/basic-syntax/compound-types.md:47 -msgid "Tuples:" -msgstr "元組:" - -#: src/basic-syntax/compound-types.md:49 -msgid "Like arrays, tuples have a fixed length." -msgstr "和陣列一樣,元組有固定的長度。" - -#: src/basic-syntax/compound-types.md:51 -msgid "Tuples group together values of different types into a compound type." -msgstr "元組會將不同型別的值組成複合型別。" - -#: src/basic-syntax/compound-types.md:53 -msgid "" -"Fields of a tuple can be accessed by the period and the index of the value, " -"e.g. `t.0`, `t.1`." -msgstr "元組的欄位可透過點號和值的索引存取,例如 `t.0`、`t.1`。" - -#: src/basic-syntax/compound-types.md:55 -msgid "" -"The empty tuple `()` is also known as the \"unit type\". It is both a type, " -"and the only valid value of that type - that is to say both the type and its " -"value are expressed as `()`. It is used to indicate, for example, that a " -"function or expression has no return value, as we'll see in a future slide. " -msgstr "" -"空白元組 `()` 也稱為「單位型別」。它既是型別,也是該型別唯一的有效值,亦即該" -"型別及其值都以 `()` 表示。舉例來說,空白元組可用於表示函式或運算式沒有任何回" -"傳值,我們會在之後的投影片看到這個例子。" - -#: src/basic-syntax/compound-types.md:59 -msgid "" -"You can think of it as `void` that can be familiar to you from other " -"programming languages." -msgstr "您可以將其視為其他程式設計語言中的 `void`,可能就不會感到陌生。" - -#: src/basic-syntax/references.md:3 -msgid "Like C++, Rust has references:" -msgstr "和 C++ 一樣,Rust 具有參照:" - -#: src/basic-syntax/references.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x: i32 = 10;\n" -" let ref_x: &mut i32 = &mut x;\n" -" *ref_x = 20;\n" -" println!(\"x: {x}\");\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/references.md:14 -msgid "Some notes:" -msgstr "注意事項:" - -#: src/basic-syntax/references.md:16 -msgid "" -"We must dereference `ref_x` when assigning to it, similar to C and C++ " -"pointers." -msgstr "指派至 `ref_x` 時,我們必須對其解除參照,這類似於 C 和 C++ 指標。" - -#: src/basic-syntax/references.md:17 -msgid "" -"Rust will auto-dereference in some cases, in particular when invoking " -"methods (try `ref_x.count_ones()`)." -msgstr "" -"在某些情況下,尤其是在叫用方法時,Rust 會自動解除參照 (請嘗試使用 `ref_x." -"count_ones()`)。" - -#: src/basic-syntax/references.md:19 -msgid "" -"References that are declared as `mut` can be bound to different values over " -"their lifetime." -msgstr "宣告為 `mut` 的參照可在其生命週期內綁定至不同的值。" - -#: src/basic-syntax/references.md:25 -msgid "" -"Be sure to note the difference between `let mut ref_x: &i32` and `let ref_x: " -"&mut i32`. The first one represents a mutable reference which can be bound " -"to different values, while the second represents a reference to a mutable " -"value." -msgstr "" -"請務必留意 `let mut ref_x: &i32` 和 `let ref_x: &mut i32` 的差異。前者代表可" -"變動的參照,可綁定至不同的值;後者則代表可變動值的參照。" - -#: src/basic-syntax/references-dangling.md:3 -msgid "Rust will statically forbid dangling references:" -msgstr "Rust 會以靜態方式禁止迷途參照:" - -#: src/basic-syntax/references-dangling.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let ref_x: &i32;\n" -" {\n" -" let x: i32 = 10;\n" -" ref_x = &x;\n" -" }\n" -" println!(\"ref_x: {ref_x}\");\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/references-dangling.md:16 -msgid "A reference is said to \"borrow\" the value it refers to." -msgstr "所謂參照項目,可說是「借用」其參照的值。" - -#: src/basic-syntax/references-dangling.md:17 -msgid "" -"Rust is tracking the lifetimes of all references to ensure they live long " -"enough." -msgstr "Rust 會追蹤所有參照項目的生命週期,確保其存留時間夠長。" - -#: src/basic-syntax/references-dangling.md:19 -msgid "We will talk more about borrowing when we get to ownership." -msgstr "我們會在講到擁有權時進一步探討「借用」。" - -#: src/basic-syntax/slices.md:3 -msgid "A slice gives you a view into a larger collection:" -msgstr "切片能讓您查看更大的集合:" - -#: src/basic-syntax/slices.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let a: [i32; 6] = [10, 20, 30, 40, 50, 60];\n" -" println!(\"a: {a:?}\");\n" -"\n" -" let s: &[i32] = &a[2..4];\n" -" println!(\"s: {s:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/slices.md:16 -msgid "Slices borrow data from the sliced type." -msgstr "切片會從切片型別借用資料。" - -#: src/basic-syntax/slices.md:16 -msgid "Question: What happens if you modify `a[3]`?" -msgstr "" - -#: src/basic-syntax/slices.md:21 -msgid "" -"We create a slice by borrowing `a` and specifying the starting and ending " -"indexes in brackets." -msgstr "我們會建立一個切片,方法是先借用 `a`,然後在括號中指定起始和結束索引。" - -#: src/basic-syntax/slices.md:23 -msgid "" -"If the slice starts at index 0, Rust’s range syntax allows us to drop the " -"starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are " -"identical." -msgstr "" -"如果切片從索引 0 開始,Rust 的範圍語法可允許我們捨棄起始索引,也就是說," -"`&a[0..a.len()]` 和 `&a[..a.len()]` 意思相同。" - -#: src/basic-syntax/slices.md:25 -msgid "" -"The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are " -"identical." -msgstr "" -"同理,最後一個索引也是如此,因此 `&a[2..a.len()]` 和 `&a[2..]` 意思相同。" - -#: src/basic-syntax/slices.md:27 -msgid "" -"To easily create a slice of the full array, we can therefore use `&a[..]`." -msgstr "因此,為了輕鬆建立完整陣列的切片,我們可以使用 `&a[..]`。" - -#: src/basic-syntax/slices.md:29 -msgid "" -"`s` is a reference to a slice of `i32`s. Notice that the type of `s` " -"(`&[i32]`) no longer mentions the array length. This allows us to perform " -"computation on slices of different sizes." -msgstr "" -"`s` 是對 `i32`s 切片的參照。請注意,`s` (`&[i32]`) 的型別不再提及陣列長度,這" -"有利於我們對不同大小的切片執行運算。" - -#: src/basic-syntax/slices.md:31 -msgid "" -"Slices always borrow from another object. In this example, `a` has to remain " -"'alive' (in scope) for at least as long as our slice. " -msgstr "" -"切片一律會從其他物件借用。在本例中,`a` 必須持續「運作」(在範圍內),時間至少" -"要和切片一樣長。" - -#: src/basic-syntax/slices.md:32 -msgid "" -"The question about modifying `a[3]` can spark an interesting discussion, but " -"the answer is that for memory safety reasons you cannot do it through `a` " -"after you created a slice, but you can read the data from both `a` and `s` " -"safely. More details will be explained in the borrow checker section." -msgstr "" - -#: src/basic-syntax/string-slices.md:1 -msgid "`String` vs `str`" -msgstr "`String` 和 `str`" - -#: src/basic-syntax/string-slices.md:3 -msgid "We can now understand the two string types in Rust:" -msgstr "現在,我們可以瞭解 Rust 中有兩種字串型別:" - -#: src/basic-syntax/string-slices.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s1: &str = \"World\";\n" -" println!(\"s1: {s1}\");\n" -"\n" -" let mut s2: String = String::from(\"Hello \");\n" -" println!(\"s2: {s2}\");\n" -" s2.push_str(s1);\n" -" println!(\"s2: {s2}\");\n" -" \n" -" let s3: &str = &s2[6..];\n" -" println!(\"s3: {s3}\");\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/string-slices.md:20 -msgid "Rust terminology:" -msgstr "以 Rust 術語來說會是這樣:" - -#: src/basic-syntax/string-slices.md:22 -msgid "`&str` an immutable reference to a string slice." -msgstr "`&str` 是對字串切片的不可變參照。" - -#: src/basic-syntax/string-slices.md:23 -msgid "`String` a mutable string buffer." -msgstr "`String` 是可變動的字串緩衝區。" - -#: src/basic-syntax/string-slices.md:27 -msgid "" -"`&str` introduces a string slice, which is an immutable reference to UTF-8 " -"encoded string data stored in a block of memory. String literals " -"(`”Hello”`), are stored in the program’s binary." -msgstr "" -"`&str` 可引進字串切片,這是對 UTF-8 編碼字串的不可變參照;該編碼字串儲存在記" -"憶體區塊中,字串常值 (`”Hello”`) 則儲存在程式的二進位檔中。" - -#: src/basic-syntax/string-slices.md:30 -msgid "" -"Rust’s `String` type is a wrapper around a vector of bytes. As with a " -"`Vec`, it is owned." -msgstr "" -"Rust 的 `String` 型別是位元組向量的包裝函式。就像使用 `Vec` 一樣,該型別有" -"專屬的擁有者。" - -#: src/basic-syntax/string-slices.md:32 -msgid "" -"As with many other types `String::from()` creates a string from a string " -"literal; `String::new()` creates a new empty string, to which string data " -"can be added using the `push()` and `push_str()` methods." -msgstr "" -"就像使用其他許多型別一樣,`String::from()` 會透過字串常值建立字串;`String::" -"new()` 則建立新的空白字串,您可以使用 `push()` 和 `push_str()` 方法將字串資料" -"加到該字串。" - -#: src/basic-syntax/string-slices.md:35 -msgid "" -"The `format!()` macro is a convenient way to generate an owned string from " -"dynamic values. It accepts the same format specification as `println!()`." -msgstr "" -"如要從動態值產生自有字串,使用 `format!()` 巨集是便捷的方法。該巨集接受與 " -"`println!()` 相同的格式規格。" - -#: src/basic-syntax/string-slices.md:38 -msgid "" -"You can borrow `&str` slices from `String` via `&` and optionally range " -"selection." -msgstr "您可以透過 `&str` 和可選的範圍選項,從 `String` 借用 `&str` 切片。" - -#: src/basic-syntax/string-slices.md:40 -msgid "" -"For C++ programmers: think of `&str` as `const char*` from C++, but the one " -"that always points to a valid string in memory. Rust `String` is a rough " -"equivalent of `std::string` from C++ (main difference: it can only contain " -"UTF-8 encoded bytes and will never use a small-string optimization)." -msgstr "" -"C++ 程式設計師請注意:您可以將 `&str` 想成 C++ 的 `const char*`,但這個 " -"`&str` 將一律指向記憶體中的有效字串。Rust 的 `String` 大致等同於 C++ 的 " -"`std::string`,主要差別是前者只能包含 UTF-8 編碼的位元組,且絕不會進行小字串" -"最佳化。" - -#: src/basic-syntax/functions.md:3 -msgid "" -"A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/" -"Fizz_buzz) interview question:" -msgstr "" -"這是知名面試問題 [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) 的 Rust " -"版本:" - -#: src/basic-syntax/functions.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" print_fizzbuzz_to(20);\n" -"}\n" -"\n" -"fn is_divisible(n: u32, divisor: u32) -> bool {\n" -" if divisor == 0 {\n" -" return false;\n" -" }\n" -" n % divisor == 0\n" -"}\n" -"\n" -"fn fizzbuzz(n: u32) -> String {\n" -" let fizz = if is_divisible(n, 3) { \"fizz\" } else { \"\" };\n" -" let buzz = if is_divisible(n, 5) { \"buzz\" } else { \"\" };\n" -" if fizz.is_empty() && buzz.is_empty() {\n" -" return format!(\"{n}\");\n" -" }\n" -" format!(\"{fizz}{buzz}\")\n" -"}\n" -"\n" -"fn print_fizzbuzz_to(n: u32) {\n" -" for i in 1..=n {\n" -" println!(\"{}\", fizzbuzz(i));\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/functions.md:35 -msgid "" -"We refer in `main` to a function written below. Neither forward declarations " -"nor headers are necessary. " -msgstr "我們在 `main` 中參照以下所寫的函式。不需前向宣告,也不需標頭。" - -#: src/basic-syntax/functions.md:36 -msgid "" -"Declaration parameters are followed by a type (the reverse of some " -"programming languages), then a return type." -msgstr "宣告參數後面接有型別 (與某些程式設計語言相反),然後才是傳回型別。" - -#: src/basic-syntax/functions.md:37 -msgid "" -"The last expression in a function body (or any block) becomes the return " -"value. Simply omit the `;` at the end of the expression." -msgstr "" -"函式主體 (或任何區塊) 中的最後一個運算式會成為回傳值。您只要省略運算式結尾的 " -"`;` 即可。" - -#: src/basic-syntax/functions.md:38 -msgid "" -"Some functions have no return value, and return the 'unit type', `()`. The " -"compiler will infer this if the `-> ()` return type is omitted." -msgstr "" -"某些函式沒有回傳值,會傳回 `()` 這個「單位型別」。如果省略 `-> ()` 傳回型別," -"編譯器則會推斷出這點。" - -#: src/basic-syntax/functions.md:39 -msgid "" -"The range expression in the `for` loop in `print_fizzbuzz_to()` contains " -"`=n`, which causes it to include the upper bound." -msgstr "" -"`print_fizzbuzz_to()` 中 `for` 迴圈的範圍運算式含有 `=n`,因此會包含上限值。" - -#: src/basic-syntax/rustdoc.md:3 -msgid "" -"All language items in Rust can be documented using special `///` syntax." -msgstr "Rust 中的所有語言項目都能以特殊的 `///` 語法來描述使用方法。" - -#: src/basic-syntax/rustdoc.md:5 -msgid "" -"```rust,editable\n" -"/// Determine whether the first argument is divisible by the second " -"argument.\n" -"///\n" -"/// If the second argument is zero, the result is false.\n" -"fn is_divisible_by(lhs: u32, rhs: u32) -> bool {\n" -" if rhs == 0 {\n" -" return false; // Corner case, early return\n" -" }\n" -" lhs % rhs == 0 // The last expression in a block is the return " -"value\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/rustdoc.md:17 -msgid "" -"The contents are treated as Markdown. All published Rust library crates are " -"automatically documented at [`docs.rs`](https://docs.rs) using the [rustdoc]" -"(https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html) tool. It is " -"idiomatic to document all public items in an API using this pattern." -msgstr "" -"系統會將內容視為 Markdown。所有已發布的 Rust 程式庫 Crate,都會使用 [rustdoc]" -"(https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html) 工具自動記錄於 " -"[`docs.rs`](https://docs.rs) 中。這種記錄 API 中所有公開項目的模式是慣用做" -"法。" - -#: src/basic-syntax/rustdoc.md:24 -msgid "" -"Show students the generated docs for the `rand` crate at [`docs.rs/rand`]" -"(https://docs.rs/rand)." -msgstr "" -"向學生展示針對 `rand` Crate 產生的文件,路徑如下:[`docs.rs/rand`](https://" -"docs.rs/rand)。" - -#: src/basic-syntax/rustdoc.md:27 -msgid "" -"This course does not include rustdoc on slides, just to save space, but in " -"real code they should be present." -msgstr "" -"本課程未在投影片中加入 rustdoc 只是為了節省空間,但在實際程式碼中不應這麼做。" - -#: src/basic-syntax/rustdoc.md:30 -msgid "" -"Inner doc comments are discussed later (in the page on modules) and need not " -"be addressed here." -msgstr "文件內註解會在稍後討論 (在模組相關頁面中),因此這裡不需提到。" - -#: src/basic-syntax/methods.md:3 -msgid "" -"Methods are functions associated with a type. The `self` argument of a " -"method is an instance of the type it is associated with:" -msgstr "" -"方法是與型別相關聯的函式。方法的 `self` 引數是與其相關聯的型別執行個體:" - -#: src/basic-syntax/methods.md:6 -msgid "" -"```rust,editable\n" -"struct Rectangle {\n" -" width: u32,\n" -" height: u32,\n" -"}\n" -"\n" -"impl Rectangle {\n" -" fn area(&self) -> u32 {\n" -" self.width * self.height\n" -" }\n" -"\n" -" fn inc_width(&mut self, delta: u32) {\n" -" self.width += delta;\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let mut rect = Rectangle { width: 10, height: 5 };\n" -" println!(\"old area: {}\", rect.area());\n" -" rect.inc_width(5);\n" -" println!(\"new area: {}\", rect.area());\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/methods.md:30 -msgid "" -"We will look much more at methods in today's exercise and in tomorrow's " -"class." -msgstr "我們將在今天的練習和明天的課程中深入探討更多方法。" - -#: src/basic-syntax/methods.md:34 -msgid "Add a `Rectangle::new` constructor and call this from `main`:" -msgstr "" - -#: src/basic-syntax/methods.md:36 -msgid "" -"```rust,editable,compile_fail\n" -"fn new(width: u32, height: u32) -> Rectangle {\n" -" Rectangle { width, height }\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/methods.md:42 -msgid "" -"Add a `Rectangle::new_square(width: u32)` constructor to illustrate that " -"constructors can take arbitrary parameters." -msgstr "" - -#: src/basic-syntax/functions-interlude.md:1 -msgid "Function Overloading" -msgstr "函式超載" - -#: src/basic-syntax/functions-interlude.md:3 -msgid "Overloading is not supported:" -msgstr "Rust 不支援超載:" - -#: src/basic-syntax/functions-interlude.md:5 -msgid "Each function has a single implementation:" -msgstr "每個函式都有單一實作項目:" - -#: src/basic-syntax/functions-interlude.md:6 -msgid "Always takes a fixed number of parameters." -msgstr "一律採用固定數量的參數。" - -#: src/basic-syntax/functions-interlude.md:7 -msgid "Always takes a single set of parameter types." -msgstr "一律採用單組參數型別。" - -#: src/basic-syntax/functions-interlude.md:8 -msgid "Default values are not supported:" -msgstr "不支援預設值:" - -#: src/basic-syntax/functions-interlude.md:9 -msgid "All call sites have the same number of arguments." -msgstr "所有呼叫的引數數目都相同。" - -#: src/basic-syntax/functions-interlude.md:10 -msgid "Macros are sometimes used as an alternative." -msgstr "有時系統會改用巨集。" - -#: src/basic-syntax/functions-interlude.md:12 -msgid "However, function parameters can be generic:" -msgstr "不過,函式參數可能為泛型:" - -#: src/basic-syntax/functions-interlude.md:14 -msgid "" -"```rust,editable\n" -"fn pick_one(a: T, b: T) -> T {\n" -" if std::process::id() % 2 == 0 { a } else { b }\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"coin toss: {}\", pick_one(\"heads\", \"tails\"));\n" -" println!(\"cash prize: {}\", pick_one(500, 1000));\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/functions-interlude.md:27 -msgid "" -"When using generics, the standard library's `Into` can provide a kind of " -"limited polymorphism on argument types. We will see more details in a later " -"section." -msgstr "" -"使用泛型時,標準程式庫的 `Into` 可以為引數型別提供一種受限的多態性。我們會" -"在後續章節中進一步說明。" - -#: src/exercises/day-1/morning.md:1 -msgid "Day 1: Morning Exercises" -msgstr "第 1 天:上午練習" - -#: src/exercises/day-1/morning.md:3 -msgid "In these exercises, we will explore two parts of Rust:" -msgstr "在這些練習中,我們將探索 Rust 的兩個部分:" - -#: src/exercises/day-1/morning.md:5 -msgid "Implicit conversions between types." -msgstr "不同型別間的隱含轉換。" - -#: src/exercises/day-1/morning.md:7 -msgid "Arrays and `for` loops." -msgstr "陣列和 `for` 迴圈。" - -#: src/exercises/day-1/morning.md:11 -msgid "A few things to consider while solving the exercises:" -msgstr "練習解題時的注意事項:" - -#: src/exercises/day-1/morning.md:13 -msgid "" -"Use a local Rust installation, if possible. This way you can get auto-" -"completion in your editor. See the page about [Using Cargo](../../cargo.md) " -"for details on installing Rust." -msgstr "" -"如果可以,請在本機安裝 Rust。這樣即可在編輯器中使用自動完成功能。如要進一步瞭" -"解如何安裝 Rust,請參閱「[使用 Cargo](../../cargo.md)」。" - -#: src/exercises/day-1/morning.md:17 -msgid "Alternatively, use the Rust Playground." -msgstr "或者,您也可以使用 Rust Playground。" - -#: src/exercises/day-1/morning.md:19 -msgid "" -"The code snippets are not editable on purpose: the inline code snippets lose " -"their state if you navigate away from the page." -msgstr "" -"系統會特意將程式碼片段設為無法編輯:如果您離開網頁,內嵌程式碼片段的狀態就會" -"遺失。" - -#: src/exercises/day-1/morning.md:22 src/exercises/day-1/afternoon.md:11 -#: src/exercises/day-2/morning.md:11 src/exercises/day-2/afternoon.md:7 -#: src/exercises/day-3/morning.md:7 src/exercises/bare-metal/morning.md:7 -#: src/exercises/bare-metal/afternoon.md:7 -#: src/exercises/concurrency/morning.md:12 -#: src/exercises/concurrency/afternoon.md:13 -msgid "" -"After looking at the exercises, you can look at the \\[solutions\\] provided." -msgstr "" - -#: src/exercises/day-1/implicit-conversions.md:3 -msgid "" -"Rust will not automatically apply _implicit conversions_ between types " -"([unlike C++](https://en.cppreference.com/w/cpp/language/" -"implicit_conversion)). You can see this in a program like this:" -msgstr "" -"Rust 不會自動在型別間套用「隱含轉換」 ([與 C++ 不同](https://en.cppreference." -"com/w/cpp/language/implicit_conversion))。您可以在類似下方的程式中發現這點:" - -#: src/exercises/day-1/implicit-conversions.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"fn multiply(x: i16, y: i16) -> i16 {\n" -" x * y\n" -"}\n" -"\n" -"fn main() {\n" -" let x: i8 = 15;\n" -" let y: i16 = 1000;\n" -"\n" -" println!(\"{x} * {y} = {}\", multiply(x, y));\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/implicit-conversions.md:19 -msgid "" -"The Rust integer types all implement the [`From`](https://doc.rust-lang." -"org/std/convert/trait.From.html) and [`Into`](https://doc.rust-lang.org/" -"std/convert/trait.Into.html) traits to let us convert between them. The " -"`From` trait has a single `from()` method and similarly, the `Into` " -"trait has a single `into()` method. Implementing these traits is how a type " -"expresses that it can be converted into another type." -msgstr "" -"Rust 整數型別全都會實作 [`From`](https://doc.rust-lang.org/std/convert/" -"trait.From.html) 和 [`Into`](https://doc.rust-lang.org/std/convert/trait." -"Into.html) 特徵,方便我們在兩者間轉換。`From` 特徵有單一的 `from() 方法;" -"同樣地,`Into` 特徵也有單一的 `into()` 方法。實作這些特徵,是型別表示自身" -"可轉換為另一種型別的方式。" - -#: src/exercises/day-1/implicit-conversions.md:25 -msgid "" -"The standard library has an implementation of `From for i16`, which " -"means that we can convert a variable `x` of type `i8` to an `i16` by " -"calling `i16::from(x)`. Or, simpler, with `x.into()`, because `From for " -"i16` implementation automatically create an implementation of `Into for " -"i8`." -msgstr "" -"標準程式庫會內有 `From for i16` 實作項目,這表示我們可以呼叫 `i16::" -"from(x)`,將類型 `i8` 的變數 `x` 轉換為 `i16`。或者,更簡單的方法是使用 `x." -"into()`,因為 `From for i16` 實作會自動建立 `Into for i8` 的實作。" - -#: src/exercises/day-1/implicit-conversions.md:30 -msgid "" -"The same applies for your own `From` implementations for your own types, so " -"it is sufficient to only implement `From` to get a respective `Into` " -"implementation automatically." -msgstr "" -"這同樣適用於您自身型別專屬的 `From` 實作,因此只要實作 `From`,就能自動取得相" -"應的 `Into` 實作。" - -#: src/exercises/day-1/implicit-conversions.md:33 -msgid "Execute the above program and look at the compiler error." -msgstr "執行上述程式,並查看編譯器錯誤。" - -#: src/exercises/day-1/implicit-conversions.md:35 -msgid "Update the code above to use `into()` to do the conversion." -msgstr "更新上述程式碼,使用 `into()` 執行轉換。" - -#: src/exercises/day-1/implicit-conversions.md:37 -msgid "" -"Change the types of `x` and `y` to other things (such as `f32`, `bool`, " -"`i128`) to see which types you can convert to which other types. Try " -"converting small types to big types and the other way around. Check the " -"[standard library documentation](https://doc.rust-lang.org/std/convert/trait." -"From.html) to see if `From` is implemented for the pairs you check." -msgstr "" -"將 `x` 和 `y` 的型別變更為其他型別 (例如 `f32`、`bool`、`i128`),查看這些型別" -"可以轉換成其他哪些型別。不妨試著將小型別轉換成大型別,反之亦然。接著參閱[標準" -"程式庫說明文件](https://doc.rust-lang.org/std/convert/trait.From.html),瞭解" -"系統是否已為您查看的配對實作 `From`。" - -#: src/exercises/day-1/for-loops.md:1 -#: src/exercises/day-1/solutions-morning.md:3 -msgid "Arrays and `for` Loops" -msgstr "陣列和 `for` 迴圈" - -#: src/exercises/day-1/for-loops.md:3 -msgid "We saw that an array can be declared like this:" -msgstr "我們已瞭解陣列的宣告方式可能如下:" - -#: src/exercises/day-1/for-loops.md:5 -msgid "" -"```rust\n" -"let array = [10, 20, 30];\n" -"```" -msgstr "" - -#: src/exercises/day-1/for-loops.md:9 -msgid "" -"You can print such an array by asking for its debug representation with `{:?}" -"`:" -msgstr "您可以使用 `{:?}` 偵錯表示法輸出這樣的陣列:" - -#: src/exercises/day-1/for-loops.md:11 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let array = [10, 20, 30];\n" -" println!(\"array: {array:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/for-loops.md:18 -msgid "" -"Rust lets you iterate over things like arrays and ranges using the `for` " -"keyword:" -msgstr "您可在 Rust 中使用 `for` 關鍵字,對陣列和範圍等項目進行疊代作業:" - -#: src/exercises/day-1/for-loops.md:21 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let array = [10, 20, 30];\n" -" print!(\"Iterating over array:\");\n" -" for n in array {\n" -" print!(\" {n}\");\n" -" }\n" -" println!();\n" -"\n" -" print!(\"Iterating over range:\");\n" -" for i in 0..3 {\n" -" print!(\" {}\", array[i]);\n" -" }\n" -" println!();\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/for-loops.md:38 -msgid "" -"Use the above to write a function `pretty_print` which pretty-print a matrix " -"and a function `transpose` which will transpose a matrix (turn rows into " -"columns):" -msgstr "" -"使用上述程式碼編寫可用用於美化矩陣排版的 `pretty_print` 函式,以及用於轉置矩" -"陣 (將列轉換為欄) 的 `transpose` 函式:" - -#: src/exercises/day-1/for-loops.md:41 -msgid "" -"```bob\n" -" ⎛⎡1 2 3⎤⎞ ⎡1 4 7⎤\n" -"\"transpose\"⎜⎢4 5 6⎥⎟ \"==\"⎢2 5 8⎥\n" -" ⎝⎣7 8 9⎦⎠ ⎣3 6 9⎦\n" -"```" -msgstr "" - -#: src/exercises/day-1/for-loops.md:47 -msgid "Hard-code both functions to operate on 3 × 3 matrices." -msgstr "為這兩個函式進行硬式編碼,以便在 3 × 3 矩陣上執行。" - -#: src/exercises/day-1/for-loops.md:49 -msgid "" -"Copy the code below to and implement the " -"functions:" -msgstr "將下方程式碼複製到 ,並實作函式:" - -#: src/exercises/day-1/for-loops.md:52 -msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {\n" -" unimplemented!()\n" -"}\n" -"\n" -"fn pretty_print(matrix: &[[i32; 3]; 3]) {\n" -" unimplemented!()\n" -"}\n" -"\n" -"fn main() {\n" -" let matrix = [\n" -" [101, 102, 103], // <-- the comment makes rustfmt add a newline\n" -" [201, 202, 203],\n" -" [301, 302, 303],\n" -" ];\n" -"\n" -" println!(\"matrix:\");\n" -" pretty_print(&matrix);\n" -"\n" -" let transposed = transpose(matrix);\n" -" println!(\"transposed:\");\n" -" pretty_print(&transposed);\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/for-loops.md:80 -msgid "Bonus Question" -msgstr "加分題" - -#: src/exercises/day-1/for-loops.md:82 -msgid "" -"Could you use `&[i32]` slices instead of hard-coded 3 × 3 matrices for your " -"argument and return types? Something like `&[&[i32]]` for a two-dimensional " -"slice-of-slices. Why or why not?" -msgstr "" -"您是否能夠使用 `&[i32]` 切片 (而非硬式編碼的 3 × 3 矩陣) 做為引數和傳回型別?" -"例如針對二維切片使用 `&[&[i32]]`。原因為何?" - -#: src/exercises/day-1/for-loops.md:87 -msgid "" -"See the [`ndarray` crate](https://docs.rs/ndarray/) for a production quality " -"implementation." -msgstr "" -"請參閱 [`ndarray` Crate](https://docs.rs/ndarray/),瞭解如何在確保實際工作環" -"境品質的情況下實作。" - -#: src/exercises/day-1/for-loops.md:92 -msgid "" -"The solution and the answer to the bonus section are available in the " -"[Solution](solutions-morning.md#arrays-and-for-loops) section." -msgstr "" -"如需加分題的解決方案和答案,請前往「[解決方案](solutions-morning.md#arrays-" -"and-for-loops)」一節。" - -#: src/basic-syntax/variables.md:3 -msgid "" -"Rust provides type safety via static typing. Variable bindings are immutable " -"by default:" -msgstr "Rust 可透過靜態型別確保型別安全。根據預設,變數綁定不可變動:" - -#: src/basic-syntax/variables.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let x: i32 = 10;\n" -" println!(\"x: {x}\");\n" -" // x = 20;\n" -" // println!(\"x: {x}\");\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/variables.md:17 -msgid "" -"Due to type inference the `i32` is optional. We will gradually show the " -"types less and less as the course progresses." -msgstr "" -"由於型別推論的關係,`i32` 為選用項目。隨著課程進行,我們會逐漸減少示範型別的" -"比例。" - -#: src/basic-syntax/variables.md:18 -msgid "" -"Note that since `println!` is a macro, `x` is not moved, even using the " -"function like syntax of `println!(\"x: {}\", x)`" -msgstr "" - -#: src/basic-syntax/type-inference.md:3 +#: src/types-and-values/inference.md msgid "Rust will look at how the variable is _used_ to determine the type:" msgstr "Rust 會觀察變數的「使用」方式,藉此判斷型別:" -#: src/basic-syntax/type-inference.md:5 -msgid "" -"```rust,editable\n" -"fn takes_u32(x: u32) {\n" -" println!(\"u32: {x}\");\n" -"}\n" -"\n" -"fn takes_i8(y: i8) {\n" -" println!(\"i8: {y}\");\n" -"}\n" -"\n" -"fn main() {\n" -" let x = 10;\n" -" let y = 20;\n" -"\n" -" takes_u32(x);\n" -" takes_i8(y);\n" -" // takes_u32(y);\n" -"}\n" -"```" -msgstr "" - -#: src/basic-syntax/type-inference.md:26 +#: src/types-and-values/inference.md msgid "" "This slide demonstrates how the Rust compiler infers types based on " "constraints given by variable declarations and usages." msgstr "" "這張投影片展示了 Rust 編譯器如何根據變數宣告和用法設下的限制來推斷型別。" -#: src/basic-syntax/type-inference.md:28 +#: src/types-and-values/inference.md msgid "" "It is very important to emphasize that variables declared like this are not " "of some sort of dynamic \"any type\" that can hold any data. The machine " @@ -3727,2651 +3231,1353 @@ msgstr "" "別。此類宣告產生的機器碼與型別的明確宣告相同。編譯器會替我們執行工作,並協助" "編寫更精簡的程式碼。" -#: src/basic-syntax/type-inference.md:32 +#: src/types-and-values/inference.md msgid "" -"The following code tells the compiler to copy into a certain generic " -"container without the code ever explicitly specifying the contained type, " -"using `_` as a placeholder:" +"When nothing constrains the type of an integer literal, Rust defaults to " +"`i32`. This sometimes appears as `{integer}` in error messages. Similarly, " +"floating-point literals default to `f64`." msgstr "" -"以下程式碼會指示編譯器使用 `_` 做為預留位置,進而複製到特定泛型容器中,而無須" -"明確指出包含的型別:" +"當整數常量的型別無任何限制時,Rust 會預設使用 `i32`。這有時會在錯誤訊息中顯示" +"為「{integer}」。同樣地,浮點常量會預設為 `f64`。" -#: src/basic-syntax/type-inference.md:34 +#: src/types-and-values/inference.md +msgid "// ERROR: no implementation for `{float} == {integer}`\n" +msgstr "// ERROR: no implementation for `{float} == {integer}`\n" + +#: src/types-and-values/exercise.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut v = Vec::new();\n" -" v.push((10, false));\n" -" v.push((20, true));\n" -" println!(\"v: {v:?}\");\n" -"\n" -" let vv = v.iter().collect::>();\n" -" println!(\"vv: {vv:?}\");\n" -"}\n" -"```" +"The first and second Fibonacci numbers are both `1`. For n>2, the n'th " +"Fibonacci number is calculated recursively as the sum of the n-1'th and " +"n-2'th Fibonacci numbers." msgstr "" +"第一和第二個費波那契數都是 `1`。當 n>2 時,第 n 個費波那契數會以遞迴方式計算" +"為第 n-1 和第 n-2 個費波那契數的和。" -#: src/basic-syntax/type-inference.md:46 +#: src/types-and-values/exercise.md msgid "" -"[`collect`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator." -"html#method.collect) relies on `FromIterator`, which [`HashSet`](https://doc." -"rust-lang.org/std/iter/trait.FromIterator.html) implements." +"Write a function `fib(n)` that calculates the n'th Fibonacci number. When " +"will this function panic?" msgstr "" +"編寫用於計算第 n 個費波那契數的 `fib(n)` 函式。這個函式何時會發生恐慌?" -#: src/basic-syntax/static-and-const.md:1 -msgid "Static and Constant Variables" -msgstr "靜態和常數變數" +#: src/types-and-values/exercise.md +msgid "// The base case.\n" +msgstr "// The base case.\n" -#: src/basic-syntax/static-and-const.md:3 -msgid "Global state is managed with static and constant variables." -msgstr "" +#: src/types-and-values/exercise.md src/control-flow-basics/exercise.md +#, fuzzy +msgid "\"Implement this\"" +msgstr "實作" -#: src/basic-syntax/static-and-const.md:6 -msgid "`const`" -msgstr "`const`" +#: src/types-and-values/exercise.md +msgid "// The recursive case.\n" +msgstr "// The recursive case.\n" -#: src/basic-syntax/static-and-const.md:7 -msgid "You can declare compile-time constants:" -msgstr "" +#: src/types-and-values/exercise.md src/types-and-values/solution.md +msgid "\"fib(n) = {}\"" +msgstr "\"fib(n) = {}\"" -#: src/basic-syntax/static-and-const.md:9 +#: src/control-flow-basics.md +#, fuzzy +msgid "[if Expressions](./control-flow-basics/if.md) (4 minutes)" +msgstr "[巨集](./control-flow-basics/macros.md) (2 分鐘)" + +#: src/control-flow-basics.md +msgid "[Loops](./control-flow-basics/loops.md) (5 minutes)" +msgstr "[迴圈](./control-flow-basics/loops.md) (5 分鐘)" + +#: src/control-flow-basics.md msgid "" -"```rust,editable\n" -"const DIGEST_SIZE: usize = 3;\n" -"const ZERO: Option = Some(42);\n" -"\n" -"fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {\n" -" let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];\n" -" for (idx, &b) in text.as_bytes().iter().enumerate() {\n" -" digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE]." -"wrapping_add(b);\n" -" }\n" -" digest\n" -"}\n" -"\n" -"fn main() {\n" -" let digest = compute_digest(\"Hello\");\n" -" println!(\"Digest: {digest:?}\");\n" -"}\n" -"```" -msgstr "" +"[break and continue](./control-flow-basics/break-continue.md) (4 minutes)" +msgstr "[break 和 continue](./control-flow-basics/break-continue.md) (4 分鐘)" -#: src/basic-syntax/static-and-const.md:29 +#: src/control-flow-basics.md msgid "" -"According to the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" -"vs-static.html) these are inlined upon use." +"[Blocks and Scopes](./control-flow-basics/blocks-and-scopes.md) (5 minutes)" msgstr "" -"根據《[Rust RFC 手冊](https://rust-lang.github.io/rfcs/0246-const-vs-static." -"html)》所述,這類值會在使用時內嵌。" +"[區塊 (block) 和範疇 (scope)](./control-flow-basics/blocks-and-scopes.md) (5 " +"分鐘)" -#: src/basic-syntax/static-and-const.md:33 -msgid "`static`" -msgstr "`static`" +#: src/control-flow-basics.md +msgid "[Functions](./control-flow-basics/functions.md) (3 minutes)" +msgstr "[函式](./control-flow-basics/functions.md) (3 分鐘)" -#: src/basic-syntax/static-and-const.md:31 -msgid "You can also declare static variables:" -msgstr "" +#: src/control-flow-basics.md +msgid "[Macros](./control-flow-basics/macros.md) (2 minutes)" +msgstr "[巨集](./control-flow-basics/macros.md) (2 分鐘)" -#: src/basic-syntax/static-and-const.md:33 +#: src/control-flow-basics.md msgid "" -"```rust,editable\n" -"static BANNER: &str = \"Welcome to RustOS 3.14\";\n" -"\n" -"fn main() {\n" -" println!(\"{BANNER}\");\n" -"}\n" -"```" +"[Exercise: Collatz Sequence](./control-flow-basics/exercise.md) (15 minutes)" +msgstr "[練習:考拉茲序列](./control-flow-basics/exercise.md) (15 分鐘)" + +#: src/control-flow-basics.md src/generics.md src/modules.md +msgid "This segment should take about 40 minutes" +msgstr "講解這個主題大約需要 40 分鐘" + +#: src/control-flow-basics/if.md +msgid "`if` expressions" +msgstr "`if` 表達式" + +#: src/control-flow-basics/if.md +msgid "" +"You use [`if` expressions](https://doc.rust-lang.org/reference/expressions/" +"if-expr.html#if-expressions) exactly like `if` statements in other languages:" +msgstr "" +"你可以像在其他語言中使用 `if` 陳述式那樣地使用 [`if` 表達式](https://doc." +"rust-lang.org/reference/expressions/if-expr.html#if-expressions):" + +#: src/control-flow-basics/if.md +msgid "\"zero!\"" +msgstr "\"zero!\"" + +#: src/control-flow-basics/if.md +msgid "\"biggish\"" +msgstr "\"biggish\"" + +#: src/control-flow-basics/if.md +msgid "\"huge\"" +msgstr "\"huge\"" + +#: src/control-flow-basics/if.md +msgid "" +"In addition, you can use `if` as an expression. The last expression of each " +"block becomes the value of the `if` expression:" +msgstr "" +"此外,你也可以將 `if` 當作表達式使用。每個區塊中的最後一行式子將成為 `if` 表" +"達式的賦值:" + +#: src/control-flow-basics/if.md +msgid "\"small\"" +msgstr "\"small\"" + +#: src/control-flow-basics/if.md +msgid "\"large\"" +msgstr "\"large\"" + +#: src/control-flow-basics/if.md +msgid "\"number size: {}\"" +msgstr "\"number size: {}\"" + +#: src/control-flow-basics/if.md +#, fuzzy +msgid "" +"Because `if` is an expression and must have a particular type, both of its " +"branch blocks must have the same type. Show what happens if you add `;` " +"after `\"small\"` in the second example." +msgstr "" +"因為 `if` 被當作表達式使用,它必須擁有一個特定的型別,因此兩個分支區塊必須擁" +"有同樣的型別。試著在第二個範例中的 `x / 2` 之後加上 `;`,並觀察其結果。" + +#: src/control-flow-basics/if.md +msgid "" +"When `if` is used in an expression, the expression must have a `;` to " +"separate it from the next statement. Remove the `;` before `println!` to see " +"the compiler error." +msgstr "" +"在運算式中使用 `if` 時,運算式須有 `;`,才能與下一個陳述式分隔。移除 " +"`println!` 前的 `;` 即可查看編譯器錯誤。" + +#: src/control-flow-basics/loops.md +msgid "There are three looping keywords in Rust: `while`, `loop`, and `for`:" +msgstr "Rust 中有三個迴圈關鍵字:`while`、`loop` 和 `for`:" + +#: src/control-flow-basics/loops.md +msgid "`while`" +msgstr "`while`" + +#: src/control-flow-basics/loops.md +msgid "" +"The [`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-" +"expr.html#predicate-loops) works much like in other languages, executing the " +"loop body as long as the condition is true." +msgstr "" +"[`while` 關鍵字](https://doc.rust-lang.org/reference/expressions/loop-expr." +"html#predicate-loops)的運作方式與其他語言非常相似:" + +#: src/control-flow-basics/loops.md +msgid "\"Final x: {x}\"" +msgstr "\"Final x: {x}\"" + +#: src/control-flow-basics/loops/for.md +#, fuzzy +msgid "" +"The [`for` loop](https://doc.rust-lang.org/std/keyword.for.html) iterates " +"over ranges of values or the items in a collection:" +msgstr "" +"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) 是具有所有權的指" +"向堆積上的資料的指標:" + +#: src/control-flow-basics/loops/for.md +msgid "\"elem: {elem}\"" +msgstr "\"elem: {elem}\"" + +#: src/control-flow-basics/loops/for.md +msgid "" +"Under the hood `for` loops use a concept called \"iterators\" to handle " +"iterating over different kinds of ranges/collections. Iterators will be " +"discussed in more detail later." msgstr "" -#: src/basic-syntax/static-and-const.md:41 +#: src/control-flow-basics/loops/for.md msgid "" -"As noted in the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" -"vs-static.html), these are not inlined upon use and have an actual " -"associated memory location. This is useful for unsafe and embedded code, " -"and the variable lives through the entirety of the program execution." +"Note that the `for` loop only iterates to `4`. Show the `1..=5` syntax for " +"an inclusive range." +msgstr "" +"請注意,`for` 迴圈只會疊代至 `4`。您可以示範 `1..=5` 語法,這代表含頭尾的範" +"圍。" + +#: src/control-flow-basics/loops/loop.md +#, fuzzy +msgid "" +"The [`loop` statement](https://doc.rust-lang.org/std/keyword.loop.html) just " +"loops forever, until a `break`." +msgstr "" +"[`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) 用於定義解構函" +"式。" + +#: src/control-flow-basics/loops/loop.md +msgid "\"{i}\"" +msgstr "\"{i}\"" + +#: src/control-flow-basics/break-continue.md +msgid "" +"If you want to immediately start the next iteration use [`continue`](https://" +"doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions)." +msgstr "" +"如果你想立即進入下一次迭代,可以使用 [`continue`](https://doc.rust-lang.org/" +"reference/expressions/loop-expr.html#continue-expressions)。" + +#: src/control-flow-basics/break-continue.md +#, fuzzy +msgid "" +"If you want to exit any kind of loop early, use [`break`](https://doc.rust-" +"lang.org/reference/expressions/loop-expr.html#break-expressions). For " +"`loop`, this can take an optional expression that becomes the value of the " +"`loop` expression." +msgstr "" +"如果你想提早跳出迴圈,可以使用 [`break`]((https://doc.rust-lang.org/" +"reference/expressions/loop-expr.html#break-expressions))," + +#: src/control-flow-basics/break-continue.md src/std-traits/exercise.md +#: src/std-traits/solution.md src/smart-pointers/trait-objects.md +#: src/modules/exercise.md src/modules/solution.md +#: src/android/build-rules/library.md +#: src/android/interoperability/cpp/rust-bridge.md +#: src/async/pitfalls/cancellation.md +msgid "\"{}\"" msgstr "" -#: src/basic-syntax/static-and-const.md:44 +#: src/control-flow-basics/break-continue/labels.md msgid "" -"We will look at mutating static data in the [chapter on Unsafe Rust](../" -"unsafe.md)." +"Both `continue` and `break` can optionally take a label argument which is " +"used to break out of nested loops:" +msgstr "" +"`continue` 以及 `break` 都可以選擇性地接收一個迴圈標籤,用來跳出巢狀迴圈中的" +"某一層:" + +#: src/control-flow-basics/break-continue/labels.md +msgid "\"elements searched: {elements_searched}\"" msgstr "" -#: src/basic-syntax/static-and-const.md:57 -msgid "Mention that `const` behaves semantically similar to C++'s `constexpr`." -msgstr "別忘了提到 `const` 的行為在語意上與 C++ 的 `constexpr` 相似。" - -#: src/basic-syntax/static-and-const.md:58 +#: src/control-flow-basics/break-continue/labels.md msgid "" -"`static`, on the other hand, is much more similar to a `const` or mutable " -"global variable in C++." -msgstr "另一方面,`static` 則更類似於 C++ 中的 `const` 或可變動的全域變數。" - -#: src/basic-syntax/static-and-const.md:60 -msgid "" -"It isn't super common that one would need a runtime evaluated constant, but " -"it is helpful and safer than using a static." +"Note that `loop` is the only looping construct which returns a non-trivial " +"value. This is because it's guaranteed to be entered at least once (unlike " +"`while` and `for` loops)." msgstr "" -"需要在執行階段評估常數的情況雖不常見,但這會比使用靜態項目更有用且安全。" +"請注意,`loop` 是唯一會傳回重要值的迴圈結構。這是因為系統保證至少會輸入一次此" +"迴圈結構,這一點不同於 `while` 和 `for` 迴圈。" -#: src/basic-syntax/scopes-shadowing.md:3 +#: src/control-flow-basics/blocks-and-scopes.md +msgid "Blocks" +msgstr "區塊" + +#: src/control-flow-basics/blocks-and-scopes.md +#, fuzzy +msgid "" +"A block in Rust contains a sequence of expressions, enclosed by braces `{}`. " +"Each block has a value and a type, which are those of the last expression of " +"the block:" +msgstr "" +"Rust 中的區塊 (Block) 包含一個數值以及一個型別:數值即為該區塊中的最後一行表" +"達式:" + +#: src/control-flow-basics/blocks-and-scopes.md +msgid "\"y: {y}\"" +msgstr "\"y: {y}\"" + +#: src/control-flow-basics/blocks-and-scopes.md +#, fuzzy +msgid "" +"If the last expression ends with `;`, then the resulting value and type is " +"`()`." +msgstr "然而,如果最後一行表達式的結尾為 `;`,則最後的數值及型別皆為 `()`。" + +#: src/control-flow-basics/blocks-and-scopes.md +msgid "" +"You can show how the value of the block changes by changing the last line in " +"the block. For instance, adding/removing a semicolon or using a `return`." +msgstr "" +"你可以藉由改變區塊中的最後一行來觀察區塊數值的變化。舉例來說,新增或刪除一個" +"分號,或者使用 `return`。" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md +msgid "A variable's scope is limited to the enclosing block." +msgstr "變數的有效範疇受限於封閉其變數的區塊。" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md msgid "" "You can shadow variables, both those from outer scopes and variables from " "the same scope:" msgstr "您可以遮蔽變量,包括來自外部範圍以及來自同一範圍的變量:" -#: src/basic-syntax/scopes-shadowing.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let a = 10;\n" -" println!(\"before: {a}\");\n" -"\n" -" {\n" -" let a = \"hello\";\n" -" println!(\"inner scope: {a}\");\n" -"\n" -" let a = true;\n" -" println!(\"shadowed in inner scope: {a}\");\n" -" }\n" -"\n" -" println!(\"after: {a}\");\n" -"}\n" -"```" -msgstr "" +#: src/control-flow-basics/blocks-and-scopes/scopes.md +msgid "\"before: {a}\"" +msgstr "\"before: {a}\"" -#: src/basic-syntax/scopes-shadowing.md:25 +#: src/control-flow-basics/blocks-and-scopes/scopes.md +#: src/std-traits/from-and-into.md src/slices-and-lifetimes/solution.md +msgid "\"hello\"" +msgstr "\"hello\"" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md +msgid "\"inner scope: {a}\"" +msgstr "\"inner scope: {a}\"" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md +msgid "\"shadowed in inner scope: {a}\"" +msgstr "\"shadowed in inner scope: {a}\"" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md +msgid "\"after: {a}\"" +msgstr "\"after: {a}\"" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md msgid "" -"Definition: Shadowing is different from mutation, because after shadowing " -"both variable's memory locations exist at the same time. Both are available " -"under the same name, depending where you use it in the code. " +"Show that a variable's scope is limited by adding a `b` in the inner block " +"in the last example, and then trying to access it outside that block." +msgstr "" +"請說明變數的範疇受到限制,做法是在最後一個範例的內部區塊中新增 `b`,然後嘗試" +"在該區塊外部存取 `b`。" + +#: src/control-flow-basics/blocks-and-scopes/scopes.md +#, fuzzy +msgid "" +"Shadowing is different from mutation, because after shadowing both " +"variable's memory locations exist at the same time. Both are available under " +"the same name, depending where you use it in the code." msgstr "" "定義:遮蔽與可變數不同,因為在遮蔽之後,兩個變數的記憶體位置會同時存在。這兩" "者可以使用同一個名稱,具體取決於您在程式碼中使用的位置。" -#: src/basic-syntax/scopes-shadowing.md:26 -msgid "A shadowing variable can have a different type. " +#: src/control-flow-basics/blocks-and-scopes/scopes.md +#, fuzzy +msgid "A shadowing variable can have a different type." msgstr "遮蔽變數可以有不同的型別。" -#: src/basic-syntax/scopes-shadowing.md:27 +#: src/control-flow-basics/blocks-and-scopes/scopes.md msgid "" "Shadowing looks obscure at first, but is convenient for holding on to values " "after `.unwrap()`." msgstr "遮蔽一開始看起來模糊不清,但對於保留 `.unwrap()` 之後的值很方便。" -#: src/basic-syntax/scopes-shadowing.md:28 +#: src/control-flow-basics/functions.md msgid "" -"The following code demonstrates why the compiler can't simply reuse memory " -"locations when shadowing an immutable variable in a scope, even if the type " -"does not change." -msgstr "" -"下列程式碼說明遮蔽範圍中不可變動的變數時,為何編譯器就是無法重複使用記憶體位" -"置 (即使型別未變更也一樣)。" +"Declaration parameters are followed by a type (the reverse of some " +"programming languages), then a return type." +msgstr "宣告參數後面接有型別 (與某些程式設計語言相反),然後才是傳回型別。" -#: src/basic-syntax/scopes-shadowing.md:30 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let a = 1;\n" -" let b = &a;\n" -" let a = a + 1;\n" -" println!(\"{a} {b}\");\n" -"}\n" -"```" -msgstr "" - -#: src/memory-management.md:3 -msgid "Traditionally, languages have fallen into two broad categories:" -msgstr "傳統上,語言大致可分為兩種:" - -#: src/memory-management.md:5 -msgid "Full control via manual memory management: C, C++, Pascal, ..." -msgstr "透過手動管理記憶體,取得完整掌控權:C、C++、Pascal..." - -#: src/memory-management.md:6 -msgid "" -"Full safety via automatic memory management at runtime: Java, Python, Go, " -"Haskell, ..." -msgstr "" -"透過在執行階段中自動管理記憶體,取得完整安全性:Java、Python、Go、Haskell..." - -#: src/memory-management.md:8 -msgid "Rust offers a new mix:" -msgstr "Rust 則融合這兩種做法:" - -#: src/memory-management.md:10 -msgid "" -"Full control _and_ safety via compile time enforcement of correct memory " -"management." -msgstr "" -"透過正確的記憶體管理編譯時間強制執行措施,「同時」取得完整的掌控權和安全性。" - -#: src/memory-management.md:13 -msgid "It does this with an explicit ownership concept." -msgstr "Rust 運用明確所有權的概念實現這一點。" - -#: src/memory-management.md:15 -msgid "First, let's refresh how memory management works." -msgstr "首先,讓我們回顧記憶體管理的運作方式。" - -#: src/memory-management/stack-vs-heap.md:1 -msgid "The Stack vs The Heap" -msgstr "堆疊與堆積" - -#: src/memory-management/stack-vs-heap.md:3 -msgid "Stack: Continuous area of memory for local variables." -msgstr "堆疊 (Stack):本機變數的連續記憶體區域。" - -#: src/memory-management/stack-vs-heap.md:4 -msgid "Values have fixed sizes known at compile time." -msgstr "值在編譯期間具有已知的固定大小。" - -#: src/memory-management/stack-vs-heap.md:5 -msgid "Extremely fast: just move a stack pointer." -msgstr "相當快速:只需移動堆疊指標。" - -#: src/memory-management/stack-vs-heap.md:6 -msgid "Easy to manage: follows function calls." -msgstr "易於管理:追蹤函式呼叫。" - -#: src/memory-management/stack-vs-heap.md:7 -msgid "Great memory locality." -msgstr "良好的記憶體區域性。" - -#: src/memory-management/stack-vs-heap.md:9 -msgid "Heap: Storage of values outside of function calls." -msgstr "堆積 (Heap):函式呼叫外的值儲存空間。" - -#: src/memory-management/stack-vs-heap.md:10 -msgid "Values have dynamic sizes determined at runtime." -msgstr "值在執行階段中以動態方式判斷大小。" - -#: src/memory-management/stack-vs-heap.md:11 -msgid "Slightly slower than the stack: some book-keeping needed." -msgstr "速度稍慢於堆疊:需要作一些記錄。" - -#: src/memory-management/stack-vs-heap.md:12 -msgid "No guarantee of memory locality." -msgstr "不保證記憶體區域性。" - -#: src/memory-management/stack.md:3 -msgid "" -"Creating a `String` puts fixed-sized data on the stack and dynamically sized " -"data on the heap:" -msgstr "" -"建立 `String` 時,系統會在堆疊上放置固定大小的資料,並在堆積上放置動態調整大" -"小的資料:" - -#: src/memory-management/stack.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s1 = String::from(\"Hello\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let s1 = String::from(\"Hello\");\n" -"}\n" -"```" - -#: src/memory-management/stack.md:12 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+----+----+ :\n" -": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" -": | len | 5 | : : +----+----+----+----+----+ :\n" -": | capacity | 5 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" -msgstr "" -"```bob\n" -" 堆疊 堆積\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+----+----+ :\n" -": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" -": | len | 5 | : : +----+----+----+----+----+ :\n" -": | capacity | 5 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" - -#: src/memory-management/stack.md:28 -msgid "" -"Mention that a `String` is backed by a `Vec`, so it has a capacity and " -"length and can grow if mutable via reallocation on the heap." -msgstr "" -"請說明 `String` 是由 `Vec` 支援,因此具有容量和長度,而且還能成長 (前提是可透" -"過堆積上的重新配置作業進行變動)。" - -#: src/memory-management/stack.md:30 -msgid "" -"If students ask about it, you can mention that the underlying memory is heap " -"allocated using the [System Allocator](https://doc.rust-lang.org/std/alloc/" -"struct.System.html) and custom allocators can be implemented using the " -"[Allocator API](https://doc.rust-lang.org/std/alloc/index.html)" -msgstr "" -"如有學員問起,您可以說明基礎記憶體是使用\\[系統配置器\\]配置的堆積,而自訂配" -"置器可以使用\\[配置器 API\\] 實作。" - -#: src/memory-management/stack.md:32 -msgid "" -"We can inspect the memory layout with `unsafe` code. However, you should " -"point out that this is rightfully unsafe!" -msgstr "" -"我們可以使用 `unsafe` 程式碼檢查記憶體配置。不過,您應指出這麼做非常不安全!" - -#: src/memory-management/stack.md:34 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut s1 = String::from(\"Hello\");\n" -" s1.push(' ');\n" -" s1.push_str(\"world\");\n" -" // DON'T DO THIS AT HOME! For educational purposes only.\n" -" // String provides no guarantees about its layout, so this could lead " -"to\n" -" // undefined behavior.\n" -" unsafe {\n" -" let (capacity, ptr, len): (usize, usize, usize) = std::mem::" -"transmute(s1);\n" -" println!(\"ptr = {ptr:#x}, len = {len}, capacity = {capacity}\");\n" -" }\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let mut s1 = String::from(\"Hello\");\n" -" s1.push(' ');\n" -" s1.push_str(\"world\");\n" -" // DON'T DO THIS AT HOME! For educational purposes only.\n" -" // String provides no guarantees about its layout, so this could lead " -"to\n" -" // undefined behavior.\n" -" unsafe {\n" -" let (capacity, ptr, len): (usize, usize, usize) = std::mem::" -"transmute(s1);\n" -" println!(\"ptr = {ptr:#x}, len = {len}, capacity = {capacity}\");\n" -" }\n" -"}\n" -"```" - -#: src/memory-management/manual.md:3 -msgid "You allocate and deallocate heap memory yourself." -msgstr "您可以自行配置及釋放堆積記憶體。" - -#: src/memory-management/manual.md:5 -msgid "" -"If not done with care, this can lead to crashes, bugs, security " -"vulnerabilities, and memory leaks." -msgstr "如果操作時不夠小心,可能會導致當機、錯誤、安全漏洞和記憶體泄漏。" - -#: src/memory-management/manual.md:7 -msgid "C Example" -msgstr "C 範例" - -#: src/memory-management/manual.md:9 -msgid "You must call `free` on every pointer you allocate with `malloc`:" -msgstr "使用 `malloc` 配置每個指標時,都必須呼叫 `free`:" - -#: src/memory-management/manual.md:11 -msgid "" -"```c\n" -"void foo(size_t n) {\n" -" int* int_array = (int*)malloc(n * sizeof(int));\n" -" //\n" -" // ... lots of code\n" -" //\n" -" free(int_array);\n" -"}\n" -"```" -msgstr "" -"```c\n" -"void foo(size_t n) {\n" -" int* int_array = (int*)malloc(n * sizeof(int));\n" -" //\n" -" // ... lots of code\n" -" //\n" -" free(int_array);\n" -"}\n" -"```" - -#: src/memory-management/manual.md:21 -msgid "" -"Memory is leaked if the function returns early between `malloc` and `free`: " -"the pointer is lost and we cannot deallocate the memory." -msgstr "" -"如果函式在 `malloc` 和 `free` 之間提早傳回記憶體,就會發生記憶體泄漏:指標遺" -"失,我們也無法釋放記憶體。" - -#: src/memory-management/scope-based.md:3 -msgid "" -"Constructors and destructors let you hook into the lifetime of an object." -msgstr "建構函式和解構函式可讓您掌握物件的生命週期。" - -#: src/memory-management/scope-based.md:5 -msgid "" -"By wrapping a pointer in an object, you can free memory when the object is " -"destroyed. The compiler guarantees that this happens, even if an exception " -"is raised." -msgstr "" -"只要在物件中包裝指標,即可在物件刪除時釋放記憶體。即使發生例外狀況,編譯器仍" -"會保證執行這項作業。" - -#: src/memory-management/scope-based.md:9 -msgid "" -"This is often called _resource acquisition is initialization_ (RAII) and " -"gives you smart pointers." -msgstr "這通常稱為「資源取得即初始化」(RAII),且會提供智慧指標。" - -#: src/memory-management/scope-based.md:12 -msgid "C++ Example" -msgstr "C++ 範例" - -#: src/memory-management/scope-based.md:14 -msgid "" -"```c++\n" -"void say_hello(std::unique_ptr person) {\n" -" std::cout << \"Hello \" << person->name << std::endl;\n" -"}\n" -"```" -msgstr "" -"```c++\n" -"void say_hello(std::unique_ptr person) {\n" -" std::cout << \"Hello \" << person->name << std::endl;\n" -"}\n" -"```" - -#: src/memory-management/scope-based.md:20 -msgid "" -"The `std::unique_ptr` object is allocated on the stack, and points to memory " -"allocated on the heap." -msgstr "`std::unique_ptr` 物件會在堆疊上配置,並指向在堆積上配置的記憶體。" - -#: src/memory-management/scope-based.md:22 -msgid "At the end of `say_hello`, the `std::unique_ptr` destructor will run." -msgstr "`say_hello` 結束時,`std::unique_ptr` 解構函式就會執行。" - -#: src/memory-management/scope-based.md:23 -msgid "The destructor frees the `Person` object it points to." -msgstr "解構函式會釋放其指向的 `Person` 物件。" - -#: src/memory-management/scope-based.md:25 -msgid "" -"Special move constructors are used when passing ownership to a function:" -msgstr "將所有權傳遞至函式時,系統會使用特殊的移動建構函式:" - -#: src/memory-management/scope-based.md:27 -msgid "" -"```c++\n" -"std::unique_ptr person = find_person(\"Carla\");\n" -"say_hello(std::move(person));\n" -"```" -msgstr "" -"```c++\n" -"std::unique_ptr person = find_person(\"Carla\");\n" -"say_hello(std::move(person));\n" -"```" - -#: src/memory-management/garbage-collection.md:1 -msgid "Automatic Memory Management" -msgstr "自動記憶體管理" - -#: src/memory-management/garbage-collection.md:3 -msgid "" -"An alternative to manual and scope-based memory management is automatic " -"memory management:" -msgstr "" -"除了手動記憶體管理和作用域式記憶體管理之外,自動記憶體管理是另一種做法:" - -#: src/memory-management/garbage-collection.md:6 -msgid "The programmer never allocates or deallocates memory explicitly." -msgstr "程式設計師一律不會明確配置或釋放記憶體。" - -#: src/memory-management/garbage-collection.md:7 -msgid "" -"A garbage collector finds unused memory and deallocates it for the " -"programmer." -msgstr "垃圾收集器會找到未使用的記憶體,並釋放給程式設計師。" - -#: src/memory-management/garbage-collection.md:9 -msgid "Java Example" -msgstr "Java 範例" - -#: src/memory-management/garbage-collection.md:11 -msgid "The `person` object is not deallocated after `sayHello` returns:" -msgstr "`sayHello` 傳回後,系統不會釋放 `person` 物件:" - -#: src/memory-management/garbage-collection.md:13 -msgid "" -"```java\n" -"void sayHello(Person person) {\n" -" System.out.println(\"Hello \" + person.getName());\n" -"}\n" -"```" -msgstr "" -"```java\n" -"void sayHello(Person person) {\n" -" System.out.println(\"Hello \" + person.getName());\n" -"}\n" -"```" - -#: src/memory-management/rust.md:1 -msgid "Memory Management in Rust" -msgstr "Rust 中的記憶體管理" - -#: src/memory-management/rust.md:3 -msgid "Memory management in Rust is a mix:" -msgstr "Rust 中的記憶體管理融合了以下特色:" - -#: src/memory-management/rust.md:5 -msgid "Safe and correct like Java, but without a garbage collector." -msgstr "像 Java 一樣安全又正確,但沒有垃圾回收機制。" - -#: src/memory-management/rust.md:6 -msgid "" -"Depending on which abstraction (or combination of abstractions) you choose, " -"can be a single unique pointer, reference counted, or atomically reference " -"counted." -msgstr "" -"可以是單一不重複指標、採用參考計數或採用原子參考計數,須視您選擇的抽象方法 " -"(或抽象方法組合) 而定。" - -#: src/memory-management/rust.md:7 -msgid "Scope-based like C++, but the compiler enforces full adherence." -msgstr "像 C++ 一樣的作用域式管理,但編譯器會強制遵循完整規定。" - -#: src/memory-management/rust.md:8 -msgid "" -"A Rust user can choose the right abstraction for the situation, some even " -"have no cost at runtime like C." -msgstr "" -"Rust 使用者可選擇適合情境的抽象方法,部分方法甚至像 C 一樣在執行階段無額外成" -"本。" - -#: src/memory-management/rust.md:10 -msgid "It achieves this by modeling _ownership_ explicitly." -msgstr "實現這種記憶體管理的方法是明確建立「所有權」模型。" - -#: src/memory-management/rust.md:14 -msgid "" -"If asked how at this point, you can mention that in Rust this is usually " -"handled by RAII wrapper types such as [Box](https://doc.rust-lang.org/std/" -"boxed/struct.Box.html), [Vec](https://doc.rust-lang.org/std/vec/struct.Vec." -"html), [Rc](https://doc.rust-lang.org/std/rc/struct.Rc.html), or [Arc]" -"(https://doc.rust-lang.org/std/sync/struct.Arc.html). These encapsulate " -"ownership and memory allocation via various means, and prevent the potential " -"errors in C." -msgstr "" -"如果這時學員詢問相關做法,您可以表示這在 Rust 中通常會以 RAII 包裝函式型別處" -"理,例如 [Box](https://doc.rust-lang.org/std/boxed/struct.Box.html)、[Vec]" -"(https://doc.rust-lang.org/std/vec/struct.Vec.html)、[Rc](https://doc.rust-" -"lang.org/std/rc/struct.Rc.html) 或 [Arc](https://doc.rust-lang.org/std/sync/" -"struct.Arc.html)。這些型別會透過多種方法封裝所有權和記憶體配置,防止在 C 中可" -"能出現的錯誤。" - -#: src/memory-management/rust.md:16 -msgid "" -"You may be asked about destructors here, the [Drop](https://doc.rust-lang." -"org/std/ops/trait.Drop.html) trait is the Rust equivalent." -msgstr "" -"這時學員可能會詢問解構函式,Rust 中的類似項目就是 [Drop](https://doc.rust-" -"lang.org/std/ops/trait.Drop.html) 特徵。" - -#: src/memory-management/comparison.md:3 -msgid "Here is a rough comparison of the memory management techniques." -msgstr "以下概略比較各種記憶體管理技巧。" - -#: src/memory-management/comparison.md:5 -msgid "Pros of Different Memory Management Techniques" -msgstr "不同記憶體管理技巧的優點" - -#: src/memory-management/comparison.md:7 src/memory-management/comparison.md:22 +#: src/control-flow-basics/functions.md #, fuzzy -msgid "Manual like C:" -msgstr "手動管理,例如 C:" +msgid "" +"The last expression in a function body (or any block) becomes the return " +"value. Simply omit the `;` at the end of the expression. The `return` " +"keyword can be used for early return, but the \"bare value\" form is " +"idiomatic at the end of a function (refactor `gcd` to use a `return`)." +msgstr "" +"函式主體 (或任何區塊) 中的最後一個運算式會成為回傳值。您只要省略運算式結尾的 " +"`;` 即可。" -#: src/memory-management/comparison.md:8 src/memory-management/comparison.md:14 -#: src/memory-management/comparison.md:17 +#: src/control-flow-basics/functions.md +msgid "" +"Some functions have no return value, and return the 'unit type', `()`. The " +"compiler will infer this if the `-> ()` return type is omitted." +msgstr "" +"某些函式沒有回傳值,會傳回 `()` 這個「單位型別」。如果省略 `-> ()` 傳回型別," +"編譯器則會推斷出這點。" + +#: src/control-flow-basics/functions.md #, fuzzy -msgid "No runtime overhead." -msgstr "沒有執行階段負擔。" +msgid "" +"Overloading is not supported -- each function has a single implementation." +msgstr "每個函式都有單一實作項目:" -#: src/memory-management/comparison.md:9 src/memory-management/comparison.md:26 +#: src/control-flow-basics/functions.md +msgid "" +"Always takes a fixed number of parameters. Default arguments are not " +"supported. Macros can be used to support variadic functions." +msgstr "" +"請一律採用定量參數。系統不支援預設引數。如要支援可變參數函式,請使用巨集。" + +#: src/control-flow-basics/functions.md #, fuzzy -msgid "Automatic like Java:" -msgstr "自動管理,例如 Java:" +msgid "" +"Always takes a single set of parameter types. These types can be generic, " +"which will be covered later." +msgstr "一律採用單組參數型別。" -#: src/memory-management/comparison.md:10 +#: src/control-flow-basics/macros.md +msgid "" +"Macros are expanded into Rust code during compilation, and can take a " +"variable number of arguments. They are distinguished by a `!` at the end. " +"The Rust standard library includes an assortment of useful macros." +msgstr "" +"巨集會在編譯期間展開為 Rust 程式碼,並可接受可變數量的引數。我們可透過結尾的 " +"`!` 來辨別巨集。Rust 標準程式庫包含各式實用巨集。" + +#: src/control-flow-basics/macros.md #, fuzzy -msgid "Fully automatic." -msgstr "完全自動化。" +msgid "" +"`println!(format, ..)` prints a line to standard output, applying formatting " +"described in [`std::fmt`](https://doc.rust-lang.org/std/fmt/index.html)." +msgstr "" +"運算子超載會透過 [`std::ops`](https://doc.rust-lang.org/std/ops/index.html): " +"內的特徵實作:" -#: src/memory-management/comparison.md:11 -#: src/memory-management/comparison.md:18 +#: src/control-flow-basics/macros.md +msgid "" +"`format!(format, ..)` works just like `println!` but returns the result as a " +"string." +msgstr "" +"`format!(format, ..)` 的運作方式與 `println!` 類似,但會以字串形式傳回結果。" + +#: src/control-flow-basics/macros.md +msgid "`dbg!(expression)` logs the value of the expression and returns it." +msgstr "`dbg!(expression)` 會記錄並傳回運算式的值。" + +#: src/control-flow-basics/macros.md +msgid "" +"`todo!()` marks a bit of code as not-yet-implemented. If executed, it will " +"panic." +msgstr "`todo!()` 可將一小段程式碼標示為尚未實作,但執行後會發生恐慌。" + +#: src/control-flow-basics/macros.md +msgid "" +"`unreachable!()` marks a bit of code as unreachable. If executed, it will " +"panic." +msgstr "`unavailable!()` 可將一小段程式碼標示為無法存取,但執行後會發生恐慌。" + +#: src/control-flow-basics/macros.md +msgid "\"{n}! = {}\"" +msgstr "\"{n}! = {}\"" + +#: src/control-flow-basics/macros.md +msgid "" +"The takeaway from this section is that these common conveniences exist, and " +"how to use them. Why they are defined as macros, and what they expand to, is " +"not especially critical." +msgstr "" +"本節的重點在於,上述的便利性不僅常見,而且確實存在,學員需瞭解如何運用。至於" +"為何將便利性定義為巨集,以及巨集展開後會變成什麼內容,則沒有那麼重要。" + +#: src/control-flow-basics/macros.md +msgid "" +"The course does not cover defining macros, but a later section will describe " +"use of derive macros." +msgstr "本課程不會探討如何定義巨集,但後續章節將說明衍生巨集的用法。" + +#: src/control-flow-basics/exercise.md +msgid "" +"The [Collatz Sequence](https://en.wikipedia.org/wiki/Collatz_conjecture) is " +"defined as follows, for an arbitrary n" +msgstr "" +"[考拉茲序列](https://zh.wikipedia.org/wiki/" +"%E8%80%83%E6%8B%89%E5%85%B9%E7%8C%9C%E6%83%B3)的定義如下,對於任意大於零的數 " +"n" + +#: src/control-flow-basics/exercise.md +msgid "1" +msgstr "1" + +#: src/control-flow-basics/exercise.md +msgid " greater than zero:" +msgstr " 大於零:" + +#: src/control-flow-basics/exercise.md +msgid "If _n" +msgstr "如果 _n" + +#: src/control-flow-basics/exercise.md +msgid "i" +msgstr "i" + +#: src/control-flow-basics/exercise.md +msgid "_ is 1, then the sequence terminates at _n" +msgstr "_ 是 1,那麼序列會終止在 _n " + +#: src/control-flow-basics/exercise.md +msgid "_." +msgstr "_。" + +#: src/control-flow-basics/exercise.md +msgid "_ is even, then _n" +msgstr "_ 是偶數,那麼 _n" + +#: src/control-flow-basics/exercise.md +msgid "i+1" +msgstr "i+1" + +#: src/control-flow-basics/exercise.md +msgid " = n" +msgstr " = n" + +#: src/control-flow-basics/exercise.md +msgid " / 2_." +msgstr " / 2_。" + +#: src/control-flow-basics/exercise.md +msgid "_ is odd, then _n" +msgstr "_ 是奇數,那麼 _n" + +#: src/control-flow-basics/exercise.md +msgid " = 3 * n" +msgstr " = 3 * n" + +#: src/control-flow-basics/exercise.md +msgid " + 1_." +msgstr " + 1_。" + +#: src/control-flow-basics/exercise.md +msgid "For example, beginning with _n" +msgstr "假設我們從 _n" + +#: src/control-flow-basics/exercise.md +msgid "_ = 3:" +msgstr "_ = 3 開始:" + +#: src/control-flow-basics/exercise.md +msgid "3 is odd, so _n" +msgstr "3 是奇數,所以 _n" + +#: src/control-flow-basics/exercise.md +msgid "2" +msgstr "2" + +#: src/control-flow-basics/exercise.md +msgid "_ = 3 * 3 + 1 = 10;" +msgstr "_ = 3 * 3 + 1 = 10;" + +#: src/control-flow-basics/exercise.md +msgid "10 is even, so _n" +msgstr "10 是偶數,所以 _n" + +#: src/control-flow-basics/exercise.md src/bare-metal/aps/better-uart.md +msgid "3" +msgstr "3" + +#: src/control-flow-basics/exercise.md +msgid "_ = 10 / 2 = 5;" +msgstr "_ = 10 / 2 = 5;" + +#: src/control-flow-basics/exercise.md +msgid "5 is odd, so _n" +msgstr "5 是奇數,所以 _n" + +#: src/control-flow-basics/exercise.md src/bare-metal/aps/better-uart.md +msgid "4" +msgstr "4" + +#: src/control-flow-basics/exercise.md +msgid "_ = 3 * 5 + 1 = 16;" +msgstr "_ = 3 * 5 + 1 = 16;" + +#: src/control-flow-basics/exercise.md +msgid "16 is even, so _n" +msgstr "16 是偶數,所以 _n" + +#: src/control-flow-basics/exercise.md +msgid "5" +msgstr "5" + +#: src/control-flow-basics/exercise.md +msgid "_ = 16 / 2 = 8;" +msgstr "_ = 16 / 2 = 8;" + +#: src/control-flow-basics/exercise.md +msgid "8 is even, so _n" +msgstr "8 是偶數,所以 _n" + +#: src/control-flow-basics/exercise.md src/bare-metal/aps/better-uart.md +msgid "6" +msgstr "6" + +#: src/control-flow-basics/exercise.md +msgid "_ = 8 / 2 = 4;" +msgstr "_ = 8 / 2 = 4;" + +#: src/control-flow-basics/exercise.md +msgid "4 is even, so _n" +msgstr "4 是偶數,所以 _n" + +#: src/control-flow-basics/exercise.md +msgid "7" +msgstr "7" + +#: src/control-flow-basics/exercise.md +msgid "_ = 4 / 2 = 2;" +msgstr "_ = 4 / 2 = 2;" + +#: src/control-flow-basics/exercise.md +msgid "2 is even, so _n" +msgstr "2 是偶數,所以 _n" + +#: src/control-flow-basics/exercise.md src/bare-metal/aps/better-uart.md +msgid "8" +msgstr "8" + +#: src/control-flow-basics/exercise.md +msgid "_ = 1; and" +msgstr "_ = 1;之後" + +#: src/control-flow-basics/exercise.md +msgid "the sequence terminates." +msgstr "序列就會終止。" + +#: src/control-flow-basics/exercise.md +msgid "" +"Write a function to calculate the length of the collatz sequence for a given " +"initial `n`." +msgstr "給定初始 `n`,請編寫一個函式來計算考拉茲序列的長度。" + +#: src/control-flow-basics/exercise.md src/control-flow-basics/solution.md +msgid "/// Determine the length of the collatz sequence beginning at `n`.\n" +msgstr "/// Determine the length of the collatz sequence beginning at `n`.\n" + +#: src/control-flow-basics/solution.md src/concurrency/scoped-threads.md +msgid "\"Length: {}\"" +msgstr "\"Length: {}\"" + +#: src/welcome-day-1-afternoon.md src/welcome-day-2-afternoon.md +#: src/welcome-day-3-afternoon.md src/welcome-day-4-afternoon.md #, fuzzy -msgid "Safe and correct." -msgstr "安全又正確。" +msgid "Welcome Back" +msgstr "歡迎" -#: src/memory-management/comparison.md:12 -#: src/memory-management/comparison.md:29 +#: src/welcome-day-1-afternoon.md +msgid "[Tuples and Arrays](./tuples-and-arrays.md) (35 minutes)" +msgstr "[元組和陣列](./tuples-and-arrays.md) (35 分鐘)" + +#: src/welcome-day-1-afternoon.md +msgid "[References](./references.md) (35 minutes)" +msgstr "[參照](./references.md) (35 分鐘)" + +#: src/welcome-day-1-afternoon.md +msgid "[User-Defined Types](./user-defined-types.md) (50 minutes)" +msgstr "[使用者定義的型別](./user-defined-types.md) (50 分鐘)" + +#: src/welcome-day-1-afternoon.md +msgid "" +"Including 10 minute breaks, this session should take about 2 hours and 15 " +"minutes" +msgstr "加上 10 分鐘的休息時間,這個課程大約需要 2 小時 15 分鐘" + +#: src/tuples-and-arrays.md +msgid "[Arrays](./tuples-and-arrays/arrays.md) (5 minutes)" +msgstr "[元組和陣列](./tuples-and-arrays/tuples-and-arrays.md) (5 分鐘)" + +#: src/tuples-and-arrays.md #, fuzzy -msgid "Scope-based like C++:" -msgstr "作用域式管理,例如 C++:" +msgid "[Tuples](./tuples-and-arrays/tuples.md) (5 minutes)" +msgstr "[元組和陣列](./tuples-and-arrays/tuples-and-arrays.md) (10 分鐘)" -#: src/memory-management/comparison.md:13 +#: src/tuples-and-arrays.md +msgid "[Array Iteration](./tuples-and-arrays/iteration.md) (3 minutes)" +msgstr "[陣列疊代](./tuples-and-arrays/iteration.md) (3 分鐘)" + +#: src/tuples-and-arrays.md +msgid "" +"[Patterns and Destructuring](./tuples-and-arrays/destructuring.md) (5 " +"minutes)" +msgstr "[解構](./tuples-and-arrays/destructuring.md) (5 分鐘)" + +#: src/tuples-and-arrays.md +msgid "[Exercise: Nested Arrays](./tuples-and-arrays/exercise.md) (15 minutes)" +msgstr "[練習:巢狀陣列](./tuples-and-arrays/exercise.md) (15 分鐘)" + +#: src/tuples-and-arrays.md src/references.md +msgid "This segment should take about 35 minutes" +msgstr "講解這個主題大約需要 35 分鐘" + +#: src/tuples-and-arrays/arrays.md #, fuzzy -msgid "Partially automatic." -msgstr "部分自動化。 \\*沒有執行階段負擔。" +msgid "" +"A value of the array type `[T; N]` holds `N` (a compile-time constant) " +"elements of the same type `T`. Note that the length of the array is _part of " +"its type_, which means that `[u8; 3]` and `[u8; 4]` are considered two " +"different types. Slices, which have a size determined at runtime, are " +"covered later." +msgstr "" +"陣列型別 `[T; N]` 的值會保留同樣屬於 `T` 型別的 `N` (編譯時間常數) 元素。請注" +"意,陣列的長度是「其型別的一部分」,也就是說 `[u8; 3]` 和 `[u8; 4]` 視為兩種" +"不同型別。" -#: src/memory-management/comparison.md:15 +#: src/tuples-and-arrays/arrays.md +msgid "" +"Try accessing an out-of-bounds array element. Array accesses are checked at " +"runtime. Rust can usually optimize these checks away, and they can be " +"avoided using unsafe Rust." +msgstr "" +"請嘗試存取超出範圍的陣列元素。系統會在執行階段檢查存取陣列的行為。Rust 通常可" +"對這類檢查進行最佳化處理,避免使用不安全的 Rust 執行這些檢查。" + +#: src/tuples-and-arrays/arrays.md +msgid "We can use literals to assign values to arrays." +msgstr "我們可以使用常值將值指派給陣列。" + +#: src/tuples-and-arrays/arrays.md #, fuzzy -msgid "Compiler-enforced scope-based like Rust:" -msgstr "由編譯器強制執行。" +msgid "" +"The `println!` macro asks for the debug implementation with the `?` format " +"parameter: `{}` gives the default output, `{:?}` gives the debug output. " +"Types such as integers and strings implement the default output, but arrays " +"only implement the debug output. This means that we must use debug output " +"here." +msgstr "" +"在主函式中,輸出陳述式會使用 `?` 格式參數要求偵錯實作:`{}` 提供預設輸出內" +"容,`{:?}` 則提供偵錯輸出內容。我們也可以使用 `{a}` 和 `{a:?}` 而不需指定格式" +"字串後方的值。" -#: src/memory-management/comparison.md:16 +#: src/tuples-and-arrays/arrays.md +msgid "" +"Adding `#`, eg `{a:#?}`, invokes a \"pretty printing\" format, which can be " +"easier to read." +msgstr "加入 `#` (例如 `{a:#?}`) 可叫用方便閱讀的「美化排版」格式。" + +#: src/tuples-and-arrays/tuples.md +msgid "Like arrays, tuples have a fixed length." +msgstr "和陣列一樣,元組有固定的長度。" + +#: src/tuples-and-arrays/tuples.md +msgid "Tuples group together values of different types into a compound type." +msgstr "元組會將不同型別的值組成複合型別。" + +#: src/tuples-and-arrays/tuples.md +msgid "" +"Fields of a tuple can be accessed by the period and the index of the value, " +"e.g. `t.0`, `t.1`." +msgstr "元組的欄位可透過點號和值的索引存取,例如 `t.0`、`t.1`。" + +#: src/tuples-and-arrays/tuples.md +msgid "" +"The empty tuple `()` is referred to as the \"unit type\" and signifies " +"absence of a return value, akin to `void` in other languages." +msgstr "" + +#: src/tuples-and-arrays/iteration.md +msgid "The `for` statement supports iterating over arrays (but not tuples)." +msgstr "`for` 陳述式支援對陣列進行疊代 (對元組則不支援)。" + +#: src/tuples-and-arrays/iteration.md +msgid "" +"This functionality uses the `IntoIterator` trait, but we haven't covered " +"that yet." +msgstr "這項功能使用 `IntoIterator` 特徵,但這部分我們尚未介紹。" + +#: src/tuples-and-arrays/iteration.md +msgid "" +"The `assert_ne!` macro is new here. There are also `assert_eq!` and `assert!" +"` macros. These are always checked while, debug-only variants like " +"`debug_assert!` compile to nothing in release builds." +msgstr "" +"`assert_ne!` 是這裡的新巨集。此外還有 `assert_eq!` 和 `assert!` 巨集。系統一" +"律會檢查這些巨集,但如果是 `debug_assert!` 這類僅供偵錯的變體,在發布子版本中" +"會編譯為空白內容。" + +#: src/tuples-and-arrays/destructuring.md +msgid "" +"When working with tuples and other structured values it's common to want to " +"extract the inner values into local variables. This can be done manually by " +"directly accessing the inner values:" +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "\"left: {left}, right: {right}\"" +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "" +"However, Rust also supports using pattern matching to destructure a larger " +"value into its constituent parts:" +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "This works with any kind of structured value:" +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "\"a: {a}, b: {b}\"" +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "" +"The patterns used here are \"irrefutable\", meaning that the compiler can " +"statically verify that the value on the right of `=` has the same structure " +"as the pattern." +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "" +"A variable name is an irrefutable pattern that always matches any value, " +"hence why we can also use `let` to declare a single variable." +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "" +"Rust also supports using patterns in conditionals, allowing for equality " +"comparison and destructuring to happen at the same time. This form of " +"pattern matching will be discussed in more detail later." +msgstr "" + +#: src/tuples-and-arrays/destructuring.md +msgid "" +"Edit the examples above to show the compiler error when the pattern doesn't " +"match the value being matched on." +msgstr "" + +#: src/tuples-and-arrays/exercise.md +msgid "Arrays can contain other arrays:" +msgstr "陣列可包含其他陣列:" + +#: src/tuples-and-arrays/exercise.md #, fuzzy -msgid "Enforced by compiler." -msgstr "沒有執行階段負擔。" - -#: src/memory-management/comparison.md:20 -msgid "Cons of Different Memory Management Techniques" -msgstr "不同記憶體管理技巧的缺點" - -#: src/memory-management/comparison.md:23 -msgid "Use-after-free." -msgstr "使用已釋放記憶體。" - -#: src/memory-management/comparison.md:24 -msgid "Double-frees." -msgstr "重複釋放。" - -#: src/memory-management/comparison.md:25 -msgid "Memory leaks." -msgstr "記憶體泄漏。" - -#: src/memory-management/comparison.md:27 -msgid "Garbage collection pauses." -msgstr "垃圾回收機制會暫停。" - -#: src/memory-management/comparison.md:28 -msgid "Destructor delays." -msgstr "解構函式會延遲。" - -#: src/memory-management/comparison.md:30 -msgid "Complex, opt-in by programmer." -msgstr "相當複雜,由程式設計師自行選用。" - -#: src/memory-management/comparison.md:31 -msgid "Potential for use-after-free." -msgstr "可能會使用已釋放記憶體。" - -#: src/memory-management/comparison.md:32 -msgid "Compiler-enforced and scope-based like Rust:" -msgstr "編譯器強制執行的範圍式管理,例如 Rust:" - -#: src/memory-management/comparison.md:33 -msgid "Some upfront complexity." -msgstr "一開始較為複雜。" - -#: src/memory-management/comparison.md:34 -msgid "Can reject valid programs." -msgstr "可能會拒絕有效程式。" - -#: src/ownership.md:3 -msgid "" -"All variable bindings have a _scope_ where they are valid and it is an error " -"to use a variable outside its scope:" -msgstr "所有變數繫結都會在特定「範圍」內有效,在範圍外使用變數會是錯誤:" - -#: src/ownership.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"struct Point(i32, i32);\n" -"\n" -"fn main() {\n" -" {\n" -" let p = Point(3, 4);\n" -" println!(\"x: {}\", p.0);\n" -" }\n" -" println!(\"y: {}\", p.1);\n" -"}\n" -"```" -msgstr "" -"```rust,editable,compile_fail\n" -"struct Point(i32, i32);\n" -"\n" -"fn main() {\n" -" {\n" -" let p = Point(3, 4);\n" -" println!(\"x: {}\", p.0);\n" -" }\n" -" println!(\"y: {}\", p.1);\n" -"}\n" -"```" - -#: src/ownership.md:18 -msgid "" -"At the end of the scope, the variable is _dropped_ and the data is freed." -msgstr "範圍結束時,變數會遭到「捨棄」,資料也會釋放。" - -#: src/ownership.md:19 -msgid "A destructor can run here to free up resources." -msgstr "解構函式可在這時執行,用來釋放資源。" - -#: src/ownership.md:20 -msgid "We say that the variable _owns_ the value." -msgstr "我們會說變數「擁有」值。" - -#: src/ownership/move-semantics.md:3 -msgid "An assignment will transfer ownership between variables:" -msgstr "指派會在變數之間轉移所有權:" - -#: src/ownership/move-semantics.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s1: String = String::from(\"Hello!\");\n" -" let s2: String = s1;\n" -" println!(\"s2: {s2}\");\n" -" // println!(\"s1: {s1}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let s1: String = String::from(\"Hello!\");\n" -" let s2: String = s1;\n" -" println!(\"s2: {s2}\");\n" -" // println!(\"s1: {s1}\");\n" -"}\n" -"```" - -#: src/ownership/move-semantics.md:14 -msgid "The assignment of `s1` to `s2` transfers ownership." -msgstr "將 `s1` 指派給 `s2` 會轉移所有權。" - -#: src/ownership/move-semantics.md:15 -msgid "The data was _moved_ from `s1` and `s1` is no longer accessible." -msgstr "資料已從 `s1`「移出」,`s1` 無法再供存取。" - -#: src/ownership/move-semantics.md:16 -msgid "When `s1` goes out of scope, nothing happens: it has no ownership." -msgstr "當 `s1` 超出範圍時,系統不會執行任何動作,因為 `s1` 沒有所有權。" - -#: src/ownership/move-semantics.md:17 -msgid "When `s2` goes out of scope, the string data is freed." -msgstr "當 `s2` 超出範圍時,系統會釋放字串資料。" - -#: src/ownership/move-semantics.md:18 -msgid "There is always _exactly_ one variable binding which owns a value." -msgstr "一律「只有」一個變數綁定會擁有值。" - -#: src/ownership/move-semantics.md:22 -msgid "" -"Mention that this is the opposite of the defaults in C++, which copies by " -"value unless you use `std::move` (and the move constructor is defined!)." -msgstr "" -"請說明這與 C++ 中的預設情形相反:您必須使用 `std::move`,且已定義移動建構函" -"式,系統才會根據值進行複製。" - -#: src/ownership/move-semantics.md:24 -msgid "In Rust, clones are explicit (by using `clone`)." -msgstr "在 Rust 中,克隆作業皆為明確設定,方法為使用 `clone`。" - -#: src/ownership/moved-strings-rust.md:3 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s1: String = String::from(\"Rust\");\n" -" let s2: String = s1;\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let s1: String = String::from(\"Rust\");\n" -" let s2: String = s1;\n" -"}\n" -"```" - -#: src/ownership/moved-strings-rust.md:10 -msgid "The heap data from `s1` is reused for `s2`." -msgstr "系統會為 `s2` 重複使用 `s1` 的堆積資料。" - -#: src/ownership/moved-strings-rust.md:11 -msgid "When `s1` goes out of scope, nothing happens (it has been moved from)." -msgstr "當 `s1` 超出範圍時,系統不會執行任何動作,因為 `s1` 已移出。" - -#: src/ownership/moved-strings-rust.md:13 -msgid "Before move to `s2`:" -msgstr "移至 `s2` 前:" - -#: src/ownership/moved-strings-rust.md:15 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+----+ :\n" -": | ptr | o---+---+-----+-->| R | u | s | t | :\n" -": | len | 4 | : : +----+----+----+----+ :\n" -": | capacity | 4 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - - - -'\n" -": :\n" -"`- - - - - - - - - - - - - -'\n" -"```" -msgstr "" -"```bob\n" -" 堆疊 堆積\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+----+ :\n" -": | ptr | o---+---+-----+-->| R | u | s | t | :\n" -": | len | 4 | : : +----+----+----+----+ :\n" -": | capacity | 4 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - - - -'\n" -": :\n" -"`- - - - - - - - - - - - - -'\n" -"```" - -#: src/ownership/moved-strings-rust.md:30 -msgid "After move to `s2`:" -msgstr "移至 `s2` 後:" - -#: src/ownership/moved-strings-rust.md:32 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 \"(inaccessible)\" : : :\n" -": +-----------+-------+ : : +----+----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| R | u | s | t | :\n" -": | len | 4 | : | : +----+----+----+----+ :\n" -": | capacity | 4 | : | : :\n" -": +-----------+-------+ : | : :\n" -": : | `- - - - - - - - - - - - - -'\n" -": s2 : |\n" -": +-----------+-------+ : |\n" -": | ptr | o---+---+--'\n" -": | len | 4 | :\n" -": | capacity | 4 | :\n" -": +-----------+-------+ :\n" -": :\n" -"`- - - - - - - - - - - - - -'\n" -"```" -msgstr "" -"```bob\n" -" 堆疊 堆積\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" -": : : :\n" -": s1 \"(inaccessible)\" : : :\n" -": +-----------+-------+ : : +----+----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| R | u | s | t | :\n" -": | len | 4 | : | : +----+----+----+----+ :\n" -": | capacity | 4 | : | : :\n" -": +-----------+-------+ : | : :\n" -": : | `- - - - - - - - - - - - - -'\n" -": s2 : |\n" -": +-----------+-------+ : |\n" -": | ptr | o---+---+--'\n" -": | len | 4 | :\n" -": | capacity | 4 | :\n" -": +-----------+-------+ :\n" -": :\n" -"`- - - - - - - - - - - - - -'\n" -"```" - -#: src/ownership/double-free-modern-cpp.md:3 -msgid "Modern C++ solves this differently:" -msgstr "現代 C++ 可使用不同方式解決這個問題:" - -#: src/ownership/double-free-modern-cpp.md:5 -msgid "" -"```c++\n" -"std::string s1 = \"Cpp\";\n" -"std::string s2 = s1; // Duplicate the data in s1.\n" -"```" -msgstr "" -"```c++\n" -"std::string s1 = \"Cpp\";\n" -"std::string s2 = s1; // 重複 s1 中的資料。\n" -"```" - -#: src/ownership/double-free-modern-cpp.md:10 -msgid "" -"The heap data from `s1` is duplicated and `s2` gets its own independent copy." -msgstr "`s1` 的堆積資料會重複,`s2` 會取得專屬的獨立副本。" - -#: src/ownership/double-free-modern-cpp.md:11 -msgid "When `s1` and `s2` go out of scope, they each free their own memory." -msgstr "當 `s1` 和 `s2` 超出範圍時,皆會釋放自己的記憶體。" - -#: src/ownership/double-free-modern-cpp.md:13 -msgid "Before copy-assignment:" -msgstr "複製指派前:" - -#: src/ownership/double-free-modern-cpp.md:16 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" -msgstr "" -"```bob\n" -" 堆疊 堆積\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" - -#: src/ownership/double-free-modern-cpp.md:30 -msgid "After copy-assignment:" -msgstr "複製指派後:" - -#: src/ownership/double-free-modern-cpp.md:32 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : : :\n" -": s2 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+-----+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" -msgstr "" -"```bob\n" -" 堆疊 堆積\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" -": : : :\n" -": s1 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+--+--+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : : :\n" -": s2 : : :\n" -": +-----------+-------+ : : +----+----+----+ :\n" -": | ptr | o---+---+-----+-->| C | p | p | :\n" -": | len | 3 | : : +----+----+----+ :\n" -": | capacity | 3 | : : :\n" -": +-----------+-------+ : : :\n" -": : `- - - - - - - - - - - -'\n" -"`- - - - - - - - - - - - - -'\n" -"```" - -#: src/ownership/moves-function-calls.md:3 -msgid "" -"When you pass a value to a function, the value is assigned to the function " -"parameter. This transfers ownership:" -msgstr "將值傳遞至函式時,該值會指派給函式參數。這麼做會轉移所有權:" - -#: src/ownership/moves-function-calls.md:6 -msgid "" -"```rust,editable\n" -"fn say_hello(name: String) {\n" -" println!(\"Hello {name}\")\n" -"}\n" -"\n" -"fn main() {\n" -" let name = String::from(\"Alice\");\n" -" say_hello(name);\n" -" // say_hello(name);\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn say_hello(name: String) {\n" -" println!(\"Hello {name}\")\n" -"}\n" -"\n" -"fn main() {\n" -" let name = String::from(\"Alice\");\n" -" say_hello(name);\n" -" // say_hello(name);\n" -"}\n" -"```" - -#: src/ownership/moves-function-calls.md:20 -msgid "" -"With the first call to `say_hello`, `main` gives up ownership of `name`. " -"Afterwards, `name` cannot be used anymore within `main`." -msgstr "" -"首次呼叫 `say_hello` 時,`main` 會放棄 `name` 的所有權。之後,`name` 就無法" -"在 `main` 內使用。" - -#: src/ownership/moves-function-calls.md:21 -msgid "" -"The heap memory allocated for `name` will be freed at the end of the " -"`say_hello` function." -msgstr "為 `name` 配置的堆積記憶體會在 `say_hello` 函式結束時釋放。" - -#: src/ownership/moves-function-calls.md:22 -msgid "" -"`main` can retain ownership if it passes `name` as a reference (`&name`) and " -"if `say_hello` accepts a reference as a parameter." -msgstr "" -"如果 `main` 以參照的形式傳送 `name` (`&name`),且 `say_hello` 能以參數的形式" -"接受參照,`main` 就可以保留所有權。" - -#: src/ownership/moves-function-calls.md:23 -msgid "" -"Alternatively, `main` can pass a clone of `name` in the first call (`name." -"clone()`)." -msgstr "另外,`main` 可在首次呼叫 (`name.clone()`) 中傳遞 `name` 的克隆。" - -#: src/ownership/moves-function-calls.md:24 -msgid "" -"Rust makes it harder than C++ to inadvertently create copies by making move " -"semantics the default, and by forcing programmers to make clones explicit." -msgstr "" -"在 Rust 中,移動語意為預設做法,且強制規定程式設計師必須明確設定克隆,因此不" -"小心建立副本的可能性就會低於在 C++ 中。" - -#: src/ownership/copy-clone.md:3 -msgid "" -"While move semantics are the default, certain types are copied by default:" -msgstr "雖然移動語意是預設做法,但某些型別的預設做法為複製:" - -#: src/ownership/copy-clone.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let x = 42;\n" -" let y = x;\n" -" println!(\"x: {x}\");\n" -" println!(\"y: {y}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let x = 42;\n" -" let y = x;\n" -" println!(\"x: {x}\");\n" -" println!(\"y: {y}\");\n" -"}\n" -"```" - -#: src/ownership/copy-clone.md:14 -msgid "These types implement the `Copy` trait." -msgstr "這些型別會實作 `Copy` 特徵。" - -#: src/ownership/copy-clone.md:16 -msgid "You can opt-in your own types to use copy semantics:" -msgstr "您可以自行選擇加入型別,使用複製語意的做法:" - -#: src/ownership/copy-clone.md:18 -msgid "" -"```rust,editable\n" -"#[derive(Copy, Clone, Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = p1;\n" -" println!(\"p1: {p1:?}\");\n" -" println!(\"p2: {p2:?}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"#[derive(Copy, Clone, Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = p1;\n" -" println!(\"p1: {p1:?}\");\n" -" println!(\"p2: {p2:?}\");\n" -"}\n" -"```" - -#: src/ownership/copy-clone.md:30 -msgid "After the assignment, both `p1` and `p2` own their own data." -msgstr "指派後,`p1` 和 `p2` 都會擁有自己的資料。" - -#: src/ownership/copy-clone.md:31 -msgid "We can also use `p1.clone()` to explicitly copy the data." -msgstr "我們也能使用 `p1.clone()` 明確複製資料。" - -#: src/ownership/copy-clone.md:35 -msgid "Copying and cloning are not the same thing:" -msgstr "複製和克隆並不相同:" - -#: src/ownership/copy-clone.md:37 -msgid "" -"Copying refers to bitwise copies of memory regions and does not work on " -"arbitrary objects." -msgstr "複製是指記憶體區域的按位元複製作業,不適用於任意物件。" - -#: src/ownership/copy-clone.md:38 -msgid "" -"Copying does not allow for custom logic (unlike copy constructors in C++)." -msgstr "複製不允許用於自訂邏輯,這與 C++ 中的複製建構函式不同。" - -#: src/ownership/copy-clone.md:39 -msgid "" -"Cloning is a more general operation and also allows for custom behavior by " -"implementing the `Clone` trait." -msgstr "克隆是較廣泛的作業,而且只要實作 `Clone` 特徵,即允許用於自訂行為。" - -#: src/ownership/copy-clone.md:40 -msgid "Copying does not work on types that implement the `Drop` trait." -msgstr "複製不適用於實作 `Drop` 特徵的型別。" - -#: src/ownership/copy-clone.md:42 src/ownership/lifetimes-function-calls.md:29 -msgid "In the above example, try the following:" -msgstr "在上述範例中,請嘗試下列操作:" - -#: src/ownership/copy-clone.md:44 -msgid "" -"Add a `String` field to `struct Point`. It will not compile because `String` " -"is not a `Copy` type." -msgstr "" -"將 `String` 欄位新增至 `struct Point`。由於 `String` 不屬於 `Copy` 型別,因此" -"不會編譯。" - -#: src/ownership/copy-clone.md:45 -msgid "" -"Remove `Copy` from the `derive` attribute. The compiler error is now in the " -"`println!` for `p1`." -msgstr "" -"從 `derive` 屬性中移除 `Copy`。編譯器錯誤現在位於 `p1` 的 `println!` 中。" - -#: src/ownership/copy-clone.md:46 -msgid "Show that it works if you clone `p1` instead." -msgstr "示範如果改為克隆 `p1`,就能正常運作。" - -#: src/ownership/copy-clone.md:48 -msgid "" -"If students ask about `derive`, it is sufficient to say that this is a way " -"to generate code in Rust at compile time. In this case the default " -"implementations of `Copy` and `Clone` traits are generated." -msgstr "" -"如有學員問起 `derive`,只需回答這是在 Rust 編譯時間中產生程式碼的方式。在這種" -"情形下,系統會產生 `Copy` 和 `Clone` 特徵的預設實作方式。" - -#: src/ownership/borrowing.md:3 -msgid "" -"Instead of transferring ownership when calling a function, you can let a " -"function _borrow_ the value:" -msgstr "您可以不必在呼叫函式時轉移所有權,而是讓函式「借用」值:" - -#: src/ownership/borrowing.md:6 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn add(p1: &Point, p2: &Point) -> Point {\n" -" Point(p1.0 + p2.0, p1.1 + p2.1)\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = Point(10, 20);\n" -" let p3 = add(&p1, &p2);\n" -" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn add(p1: &Point, p2: &Point) -> Point {\n" -" Point(p1.0 + p2.0, p1.1 + p2.1)\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = Point(10, 20);\n" -" let p3 = add(&p1, &p2);\n" -" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" -"}\n" -"```" - -#: src/ownership/borrowing.md:22 -msgid "The `add` function _borrows_ two points and returns a new point." -msgstr "`add` 函式會「借用」兩個點,並傳回新的點。" - -#: src/ownership/borrowing.md:23 -msgid "The caller retains ownership of the inputs." -msgstr "呼叫端會保留輸入內容的所有權。" - -#: src/ownership/borrowing.md:27 -msgid "Notes on stack returns:" -msgstr "有關堆疊回傳的注意事項:" - -#: src/ownership/borrowing.md:28 -msgid "" -"Demonstrate that the return from `add` is cheap because the compiler can " -"eliminate the copy operation. Change the above code to print stack addresses " -"and run it on the [Playground](https://play.rust-lang.org/). In the " -"\"DEBUG\" optimization level, the addresses should change, while they stay " -"the same when changing to the \"RELEASE\" setting:" -msgstr "" -"示範因為編譯器可刪除複製操作,所以 `add` 回傳的成本較低。變更上述程式碼來顯示" -"堆疊位址,並在 [Playground](https://play.rust-lang.org/) 上執行。在「DEBUG」" -"最佳化等級中,位址應變更,但在變更為「RELEASE」設定時,位址應維持不變:" - -#: src/ownership/borrowing.md:30 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn add(p1: &Point, p2: &Point) -> Point {\n" -" let p = Point(p1.0 + p2.0, p1.1 + p2.1);\n" -" println!(\"&p.0: {:p}\", &p.0);\n" -" p\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = Point(10, 20);\n" -" let p3 = add(&p1, &p2);\n" -" println!(\"&p3.0: {:p}\", &p3.0);\n" -" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn add(p1: &Point, p2: &Point) -> Point {\n" -" let p = Point(p1.0 + p2.0, p1.1 + p2.1);\n" -" println!(\"&p.0: {:p}\", &p.0);\n" -" p\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point(3, 4);\n" -" let p2 = Point(10, 20);\n" -" let p3 = add(&p1, &p2);\n" -" println!(\"&p3.0: {:p}\", &p3.0);\n" -" println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" -"}\n" -"```" - -#: src/ownership/borrowing.md:48 -msgid "The Rust compiler can do return value optimization (RVO)." -msgstr "Rust 編譯器可以執行回傳值最佳化 (RVO)。" - -#: src/ownership/borrowing.md:49 -msgid "" -"In C++, copy elision has to be defined in the language specification because " -"constructors can have side effects. In Rust, this is not an issue at all. If " -"RVO did not happen, Rust will always performs a simple and efficient " -"`memcpy` copy." -msgstr "" -"在 C++ 中,複製省略必須定義在語言規格內,因為建構函式可能有連帶效果。在 Rust " -"中,這完全不是問題。如未發生 RVO,Rust 一律會執行簡單有效的 `memcpy` 複製作" -"業。" - -#: src/ownership/shared-unique-borrows.md:3 -msgid "Rust puts constraints on the ways you can borrow values:" -msgstr "Rust 會限制借用值的方式:" - -#: src/ownership/shared-unique-borrows.md:5 -msgid "You can have one or more `&T` values at any given time, _or_" -msgstr "隨時擁有一或多個 `&T` 值,「或是」" - -#: src/ownership/shared-unique-borrows.md:6 -msgid "You can have exactly one `&mut T` value." -msgstr "只擁有一個 `&mut T` 值。" - -#: src/ownership/shared-unique-borrows.md:8 -msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let mut a: i32 = 10;\n" -" let b: &i32 = &a;\n" -"\n" -" {\n" -" let c: &mut i32 = &mut a;\n" -" *c = 20;\n" -" }\n" -"\n" -" println!(\"a: {a}\");\n" -" println!(\"b: {b}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let mut a: i32 = 10;\n" -" let b: &i32 = &a;\n" -"\n" -" {\n" -" let c: &mut i32 = &mut a;\n" -" *c = 20;\n" -" }\n" -"\n" -" println!(\"a: {a}\");\n" -" println!(\"b: {b}\");\n" -"}\n" -"```" - -#: src/ownership/shared-unique-borrows.md:25 -msgid "" -"The above code does not compile because `a` is borrowed as mutable (through " -"`c`) and as immutable (through `b`) at the same time." -msgstr "" -"上述程式碼不會編譯,因為系統會同時透過 `c` 和 `b`,以可變動項和不可變動項的格" -"式借用 `a`。" - -#: src/ownership/shared-unique-borrows.md:26 -msgid "" -"Move the `println!` statement for `b` before the scope that introduces `c` " -"to make the code compile." -msgstr "請將 `b` 的 `println!` 陳述式移到導入 `c` 的範圍前,即可編譯程式碼。" - -#: src/ownership/shared-unique-borrows.md:27 -msgid "" -"After that change, the compiler realizes that `b` is only ever used before " -"the new mutable borrow of `a` through `c`. This is a feature of the borrow " -"checker called \"non-lexical lifetimes\"." -msgstr "" -"經過該變更後,編譯器會發現系統使用 `b` 的時間,只會在新可變動項透過 `c` 借用 " -"`a` 之前。這是借用檢查器中的功能,稱為「非詞彙生命週期」(non-lexical " -"lifetimes)。" - -#: src/ownership/lifetimes.md:3 -msgid "A borrowed value has a _lifetime_:" -msgstr "借用的值具有「生命週期」:" - -#: src/ownership/lifetimes.md:5 -msgid "The lifetime can be implicit: `add(p1: &Point, p2: &Point) -> Point`." -msgstr "生命週期可以採用隱含方式:`add(p1: &Point, p2: &Point) -> Point`。" - -#: src/ownership/lifetimes.md:6 -msgid "Lifetimes can also be explicit: `&'a Point`, `&'document str`." -msgstr "生命週期也可以採用明確方式:`&'a Point`、`&'document str`。" - -#: src/ownership/lifetimes.md:7 src/ownership/lifetimes-function-calls.md:23 -msgid "" -"Read `&'a Point` as \"a borrowed `Point` which is valid for at least the " -"lifetime `a`\"." -msgstr "請將 `&'a Point` 讀做「至少對生命週期 `a` 有效的借用 `Point`」。" - -#: src/ownership/lifetimes.md:9 -msgid "" -"Lifetimes are always inferred by the compiler: you cannot assign a lifetime " -"yourself." -msgstr "生命週期一律會由編譯器推論:您無法自行指派生命週期。" - -#: src/ownership/lifetimes.md:11 -msgid "" -"Lifetime annotations create constraints; the compiler verifies that there is " -"a valid solution." -msgstr "生命週期註解會建立限制;編譯器會驗證是否有有效的解決方案。" - -#: src/ownership/lifetimes.md:13 -msgid "" -"Lifetimes for function arguments and return values must be fully specified, " -"but Rust allows these to be elided in most cases with [a few simple rules]" -"(https://doc.rust-lang.org/nomicon/lifetime-elision.html)." -msgstr "" -"請務必完整指定函式引數和回傳值的生命週期,不過在大部分情況下,Rust 允許使用 " -"[一些簡單規則](https://doc.rust-lang.org/nomicon/lifetime-elision.html) 省略" -"這些生命週期。" - -#: src/ownership/lifetimes-function-calls.md:3 -msgid "" -"In addition to borrowing its arguments, a function can return a borrowed " -"value:" -msgstr "除了借用引數,函式也可以傳回借用的值:" - -#: src/ownership/lifetimes-function-calls.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" -" if p1.0 < p2.0 { p1 } else { p2 }\n" -"}\n" -"\n" -"fn main() {\n" -" let p1: Point = Point(10, 10);\n" -" let p2: Point = Point(20, 20);\n" -" let p3: &Point = left_most(&p1, &p2);\n" -" println!(\"left-most point: {:?}\", p3);\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" -" if p1.0 < p2.0 { p1 } else { p2 }\n" -"}\n" -"\n" -"fn main() {\n" -" let p1: Point = Point(10, 10);\n" -" let p2: Point = Point(20, 20);\n" -" let p3: &Point = left_most(&p1, &p2);\n" -" println!(\"left-most point: {:?}\", p3);\n" -"}\n" -"```" - -#: src/ownership/lifetimes-function-calls.md:21 -msgid "`'a` is a generic parameter, it is inferred by the compiler." -msgstr "`'a` 是由編譯器推論的泛型參數。" - -#: src/ownership/lifetimes-function-calls.md:22 -msgid "Lifetimes start with `'` and `'a` is a typical default name." -msgstr "生命週期的開頭為 `'`,一般預設名稱為 `'a`。" - -#: src/ownership/lifetimes-function-calls.md:25 -msgid "" -"The _at least_ part is important when parameters are in different scopes." -msgstr "如果參數位於不同的範圍,「至少」一詞就至關重要。" - -#: src/ownership/lifetimes-function-calls.md:31 -msgid "" -"Move the declaration of `p2` and `p3` into a new scope (`{ ... }`), " -"resulting in the following code:" -msgstr "將 `p2` 和 `p3` 的宣告移至新範圍 (`{ ... }`),會產生以下程式碼:" - -#: src/ownership/lifetimes-function-calls.md:32 -msgid "" -"```rust,ignore\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" -" if p1.0 < p2.0 { p1 } else { p2 }\n" -"}\n" -"\n" -"fn main() {\n" -" let p1: Point = Point(10, 10);\n" -" let p3: &Point;\n" -" {\n" -" let p2: Point = Point(20, 20);\n" -" p3 = left_most(&p1, &p2);\n" -" }\n" -" println!(\"left-most point: {:?}\", p3);\n" -"}\n" -"```" -msgstr "" -"```rust,ignore\n" -"#[derive(Debug)]\n" -"struct Point(i32, i32);\n" -"\n" -"fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" -" if p1.0 < p2.0 { p1 } else { p2 }\n" -"}\n" -"\n" -"fn main() {\n" -" let p1: Point = Point(10, 10);\n" -" let p3: &Point;\n" -" {\n" -" let p2: Point = Point(20, 20);\n" -" p3 = left_most(&p1, &p2);\n" -" }\n" -" println!(\"left-most point: {:?}\", p3);\n" -"}\n" -"```" - -#: src/ownership/lifetimes-function-calls.md:50 -msgid "Note how this does not compile since `p3` outlives `p2`." -msgstr "請注意,這在 `p3` 超越 `p2` 並繼續留存後,就沒有編譯。" - -#: src/ownership/lifetimes-function-calls.md:52 -msgid "" -"Reset the workspace and change the function signature to `fn left_most<'a, " -"'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will not compile " -"because the relationship between the lifetimes `'a` and `'b` is unclear." -msgstr "" -"重設工作區,並將函式簽章變更為 `fn left_most<'a, 'b>(p1: &'a Point, p2: &'a " -"Point) -> &'b Point`。這不會編譯,因為生命週期 `'a` 和 `'b` 之間的關係不明" -"確。" - -#: src/ownership/lifetimes-function-calls.md:53 -msgid "Another way to explain it:" -msgstr "另一種說明方式:" - -#: src/ownership/lifetimes-function-calls.md:54 -msgid "" -"Two references to two values are borrowed by a function and the function " -"returns another reference." -msgstr "函式會借用兩個值的兩個參照,而函式會傳回另一個參照。" - -#: src/ownership/lifetimes-function-calls.md:56 -msgid "" -"It must have come from one of those two inputs (or from a global variable)." -msgstr "該參照必須來自這兩種輸入來源的其中之一 (或來自全域變數)。" - -#: src/ownership/lifetimes-function-calls.md:57 -msgid "" -"Which one is it? The compiler needs to know, so at the call site the " -"returned reference is not used for longer than a variable from where the " -"reference came from." -msgstr "" -"究竟是哪一個來源?編譯器需要知道來源為何,因此在呼叫點上,所傳回參照的使用時" -"間不會長於來自參照來源的變數。" - -#: src/ownership/lifetimes-data-structures.md:3 -msgid "" -"If a data type stores borrowed data, it must be annotated with a lifetime:" -msgstr "如果資料型別會儲存借用的資料,則必須使用生命週期註解:" - -#: src/ownership/lifetimes-data-structures.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Highlight<'doc>(&'doc str);\n" -"\n" -"fn erase(text: String) {\n" -" println!(\"Bye {text}!\");\n" -"}\n" -"\n" -"fn main() {\n" -" let text = String::from(\"The quick brown fox jumps over the lazy dog." -"\");\n" -" let fox = Highlight(&text[4..19]);\n" -" let dog = Highlight(&text[35..43]);\n" -" // erase(text);\n" -" println!(\"{fox:?}\");\n" -" println!(\"{dog:?}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Highlight<'doc>(&'doc str);\n" -"\n" -"fn erase(text: String) {\n" -" println!(\"Bye {text}!\");\n" -"}\n" -"\n" -"fn main() {\n" -" let text = String::from(\"The quick brown fox jumps over the lazy dog." -"\");\n" -" let fox = Highlight(&text[4..19]);\n" -" let dog = Highlight(&text[35..43]);\n" -" // erase(text);\n" -" println!(\"{fox:?}\");\n" -" println!(\"{dog:?}\");\n" -"}\n" -"```" - -#: src/ownership/lifetimes-data-structures.md:25 -msgid "" -"In the above example, the annotation on `Highlight` enforces that the data " -"underlying the contained `&str` lives at least as long as any instance of " -"`Highlight` that uses that data." -msgstr "" -"在上述範例中,`Highlight` 的註解會強制執行以下規定:若是包含在內的 `&str` 的" -"基礎資料,留存時間應至少和使用該資料的所有 `Highlight` 例項一樣長。" - -#: src/ownership/lifetimes-data-structures.md:26 -msgid "" -"If `text` is consumed before the end of the lifetime of `fox` (or `dog`), " -"the borrow checker throws an error." -msgstr "" -"如果在 `fox` (或 `dog`) 的生命週期結束前消耗 `text`,借用檢查器會擲回錯誤。" - -#: src/ownership/lifetimes-data-structures.md:27 -msgid "" -"Types with borrowed data force users to hold on to the original data. This " -"can be useful for creating lightweight views, but it generally makes them " -"somewhat harder to use." -msgstr "" -"含有借用資料的型別會強制要求使用者保留原始資料。這在建立輕量檢視畫面可能很實" -"用,但通常也會增加使用難度。" - -#: src/ownership/lifetimes-data-structures.md:28 -msgid "When possible, make data structures own their data directly." -msgstr "請盡可能讓資料結構直接擁有資料。" - -#: src/ownership/lifetimes-data-structures.md:29 -msgid "" -"Some structs with multiple references inside can have more than one lifetime " -"annotation. This can be necessary if there is a need to describe lifetime " -"relationships between the references themselves, in addition to the lifetime " -"of the struct itself. Those are very advanced use cases." -msgstr "" -"某些內含多個參照的結構體可擁有多個生命週期註解。如果除了結構體的生命週期之" -"外,還需要描述參照之間的生命週期關係,就可能有必要擁有多個生命週期註解。那些" -"是相當進階的用途。" - -#: src/exercises/day-1/afternoon.md:1 -msgid "Day 1: Afternoon Exercises" -msgstr "第 1 天:下午練習" - -#: src/exercises/day-1/afternoon.md:3 -msgid "We will look at two things:" -msgstr "我們將著重在以下兩點:" - -#: src/exercises/day-1/afternoon.md:5 -msgid "A small book library," -msgstr "" - -#: src/exercises/day-1/afternoon.md:7 -msgid "Iterators and ownership (hard)." -msgstr "" - -#: src/exercises/day-2/book-library.md:3 -msgid "" -"We will learn much more about structs and the `Vec` type tomorrow. For " -"now, you just need to know part of its API:" -msgstr "" -"明天我們會進一步講解結構體和 `Vec` 型別。現階段,您只需要瞭解相關 API 的部" -"分內容:" - -#: src/exercises/day-1/book-library.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut vec = vec![10, 20];\n" -" vec.push(30);\n" -" let midpoint = vec.len() / 2;\n" -" println!(\"middle value: {}\", vec[midpoint]);\n" -" for item in &vec {\n" -" println!(\"item: {item}\");\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/book-library.md:18 -msgid "" -"Use this to create a library application. Copy the code below to and update the types to make it compile:" -msgstr "" - -#: src/exercises/day-1/book-library.md:21 -msgid "" -"```rust,should_panic\n" -"struct Library {\n" -" books: Vec,\n" -"}\n" -"\n" -"struct Book {\n" -" title: String,\n" -" year: u16,\n" -"}\n" -"\n" -"impl Book {\n" -" // This is a constructor, used below.\n" -" fn new(title: &str, year: u16) -> Book {\n" -" Book {\n" -" title: String::from(title),\n" -" year,\n" -" }\n" -" }\n" -"}\n" -"\n" -"// Implement the methods below. Update the `self` parameter to\n" -"// indicate the method's required level of ownership over the object:\n" -"//\n" -"// - `&self` for shared read-only access,\n" -"// - `&mut self` for unique and mutable access,\n" -"// - `self` for unique access by value.\n" -"impl Library {\n" -" fn new() -> Library {\n" -" todo!(\"Initialize and return a `Library` value\")\n" -" }\n" -"\n" -" //fn len(self) -> usize {\n" -" // todo!(\"Return the length of `self.books`\")\n" -" //}\n" -"\n" -" //fn is_empty(self) -> bool {\n" -" // todo!(\"Return `true` if `self.books` is empty\")\n" -" //}\n" -"\n" -" //fn add_book(self, book: Book) {\n" -" // todo!(\"Add a new book to `self.books`\")\n" -" //}\n" -"\n" -" //fn print_books(self) {\n" -" // todo!(\"Iterate over `self.books` and each book's title and " -"year\")\n" -" //}\n" -"\n" -" //fn oldest_book(self) -> Option<&Book> {\n" -" // todo!(\"Return a reference to the oldest book (if any)\")\n" -" //}\n" -"}\n" -"\n" -"// This shows the desired behavior. Uncomment the code below and\n" -"// implement the missing methods. You will need to update the\n" -"// method signatures, including the \"self\" parameter! You may\n" -"// also need to update the variable bindings within main.\n" -"fn main() {\n" -" let library = Library::new();\n" -"\n" -" //println!(\"The library is empty: {}\", library.is_empty());\n" -" //\n" -" //library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" //library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" //\n" -" //println!(\"The library is no longer empty: {}\", library.is_empty());\n" -" //\n" -" //\n" -" //library.print_books();\n" -" //\n" -" //match library.oldest_book() {\n" -" // Some(book) => println!(\"The oldest book is {}\", book.title),\n" -" // None => println!(\"The library is empty!\"),\n" -" //}\n" -" //\n" -" //println!(\"The library has {} books\", library.len());\n" -" //library.print_books();\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/book-library.md:102 -msgid "[Solution](solutions-afternoon.md#designing-a-library)" -msgstr "[解決方案](solutions-afternoon.md#designing-a-library)" - -#: src/exercises/day-2/iterators-and-ownership.md:3 -msgid "" -"The ownership model of Rust affects many APIs. An example of this is the " -"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " -"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " -"traits." -msgstr "" -"Rust 的擁有權模型會影響許多 API。[`Iterator`](https://doc.rust-lang.org/std/" -"iter/trait.Iterator.html) 和 [`IntoIterator`](https://doc.rust-lang.org/std/" -"iter/trait.IntoIterator.html) 特徵就是一例。" - -#: src/exercises/day-2/iterators-and-ownership.md:8 src/bare-metal/no_std.md:28 -msgid "`Iterator`" -msgstr "`Iterator`" - -#: src/exercises/day-2/iterators-and-ownership.md:10 -msgid "" -"Traits are like interfaces: they describe behavior (methods) for a type. The " -"`Iterator` trait simply says that you can call `next` until you get `None` " -"back:" -msgstr "" -"特徵就像介面一樣,可以說明型別的行為 (方法)。`Iterator` 特徵就是指您可以呼叫 " -"`next`,直到取回 `None` 為止:" - -#: src/exercises/day-1/iterators-and-ownership.md:13 -msgid "" -"```rust\n" -"pub trait Iterator {\n" -" type Item;\n" -" fn next(&mut self) -> Option;\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/iterators-and-ownership.md:20 -msgid "You use this trait like this:" -msgstr "您可以像下方這樣使用這個特徵:" - -#: src/exercises/day-1/iterators-and-ownership.md:22 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v: Vec = vec![10, 20, 30];\n" -" let mut iter = v.iter();\n" -"\n" -" println!(\"v[0]: {:?}\", iter.next());\n" -" println!(\"v[1]: {:?}\", iter.next());\n" -" println!(\"v[2]: {:?}\", iter.next());\n" -" println!(\"No more items: {:?}\", iter.next());\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/iterators-and-ownership.md:34 -msgid "What is the type returned by the iterator? Test your answer here:" -msgstr "如要瞭解疊代器傳回的型別為何,不妨在這裡測試答案:" - -#: src/exercises/day-1/iterators-and-ownership.md:36 -msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let v: Vec = vec![10, 20, 30];\n" -" let mut iter = v.iter();\n" -"\n" -" let v0: Option<..> = iter.next();\n" -" println!(\"v0: {v0:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/iterators-and-ownership.md:46 -msgid "Why is this type used?" -msgstr "思考一下,為什麼會使用這種型別?" - -#: src/exercises/day-2/iterators-and-ownership.md:48 -msgid "`IntoIterator`" -msgstr "`IntoIterator`" - -#: src/exercises/day-2/iterators-and-ownership.md:50 -msgid "" -"The `Iterator` trait tells you how to _iterate_ once you have created an " -"iterator. The related trait `IntoIterator` tells you how to create the " -"iterator:" -msgstr "" -"`Iterator` 特徵會告訴您如何在建立疊代器後進行「疊代」。相關特徵 " -"`IntoIterator` 則會說明如何建立疊代器:" - -#: src/exercises/day-1/iterators-and-ownership.md:53 -msgid "" -"```rust\n" -"pub trait IntoIterator {\n" -" type Item;\n" -" type IntoIter: Iterator;\n" -"\n" -" fn into_iter(self) -> Self::IntoIter;\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/iterators-and-ownership.md:62 -msgid "" -"The syntax here means that every implementation of `IntoIterator` must " -"declare two types:" -msgstr "這裡的語法表示每個 `IntoIterator` 的實作都必須宣告兩種型別:" - -#: src/exercises/day-2/iterators-and-ownership.md:65 -msgid "`Item`: the type we iterate over, such as `i8`," -msgstr "`Item`:進行疊代的型別,例如 `i8`。" - -#: src/exercises/day-2/iterators-and-ownership.md:66 -msgid "`IntoIter`: the `Iterator` type returned by the `into_iter` method." -msgstr "`IntoIter`:`into_iter` 方法傳回的 `Iterator` 型別。" - -#: src/exercises/day-2/iterators-and-ownership.md:68 -msgid "" -"Note that `IntoIter` and `Item` are linked: the iterator must have the same " -"`Item` type, which means that it returns `Option`" -msgstr "" -"請注意,`IntoIter` 和 `Item` 已建立連結:疊代器必須具有相同的 `Item` 型別,表" -"示會傳回 `Option`。" - -#: src/exercises/day-2/iterators-and-ownership.md:71 -msgid "Like before, what is the type returned by the iterator?" -msgstr "和先前一樣,思考疊代器傳回的型別為何。" - -#: src/exercises/day-1/iterators-and-ownership.md:73 -msgid "" -"```rust,editable,compile_fail\n" -"fn main() {\n" -" let v: Vec = vec![String::from(\"foo\"), String::" -"from(\"bar\")];\n" -" let mut iter = v.into_iter();\n" -"\n" -" let v0: Option<..> = iter.next();\n" -" println!(\"v0: {v0:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/iterators-and-ownership.md:83 -msgid "`for` Loops" -msgstr "`for` 迴圈" - -#: src/exercises/day-2/iterators-and-ownership.md:85 -msgid "" -"Now that we know both `Iterator` and `IntoIterator`, we can build `for` " -"loops. They call `into_iter()` on an expression and iterates over the " -"resulting iterator:" -msgstr "" -"現在我們已瞭解 `Iterator` 和 `IntoIterator`,可以建構 `for` 迴圈了。這會在運" -"算式上呼叫 `into_iter()`,並對產生的疊代器進行疊代:" - -#: src/exercises/day-1/iterators-and-ownership.md:89 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v: Vec = vec![String::from(\"foo\"), String::" -"from(\"bar\")];\n" -"\n" -" for word in &v {\n" -" println!(\"word: {word}\");\n" -" }\n" -"\n" -" for word in v {\n" -" println!(\"word: {word}\");\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/iterators-and-ownership.md:103 -msgid "What is the type of `word` in each loop?" +msgid "What is the type of this variable?" msgstr "思考一下,每個迴圈中的 `word` 型別為何?" -#: src/exercises/day-1/iterators-and-ownership.md:105 -msgid "" -"Experiment with the code above and then consult the documentation for [`impl " -"IntoIterator for &Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." -"html#impl-IntoIterator-for-%26%27a%20Vec%3CT%2C%20A%3E) and [`impl " -"IntoIterator for Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." -"html#impl-IntoIterator-for-Vec%3CT%2C%20A%3E) to check your answers." -msgstr "" - -#: src/welcome-day-2.md:1 -msgid "Welcome to Day 2" -msgstr "歡迎參加第 2 天課程" - -#: src/welcome-day-2.md:3 -msgid "Now that we have seen a fair amount of Rust, we will continue with:" -msgstr "您目前對 Rust 已有相當程度的認識,接下來我們將繼續講解以下概念:" - -#: src/welcome-day-2.md:5 +#: src/tuples-and-arrays/exercise.md #, fuzzy -msgid "Structs, enums, methods." -msgstr "結構體和方法。" - -#: src/welcome-day-1.md:12 -msgid "Pattern matching: destructuring enums, structs, and arrays." -msgstr "模式配對:解構列舉、結構和陣列。" - -#: src/welcome-day-1.md:9 msgid "" -"Control flow constructs: `if`, `if let`, `while`, `while let`, `break`, and " -"`continue`." +"Use an array such as the above to write a function `transpose` which will " +"transpose a matrix (turn rows into columns):" msgstr "" -"控制流程結構:`if`、`if let`、`while`、`while let`、`break` 和 `continue`。" +"使用上述程式碼編寫可用用於美化矩陣排版的 `pretty_print` 函式,以及用於轉置矩" +"陣 (將列轉換為欄) 的 `transpose` 函式:" -#: src/welcome-day-2.md:12 +#: src/tuples-and-arrays/exercise.md +msgid "Hard-code both functions to operate on 3 × 3 matrices." +msgstr "為這兩個函式進行硬式編碼,以便在 3 × 3 矩陣上執行。" + +#: src/tuples-and-arrays/exercise.md msgid "" -"The Standard Library: `String`, `Option` and `Result`, `Vec`, `HashMap`, " -"`Rc` and `Arc`." +"Copy the code below to and implement the " +"functions:" +msgstr "將下方程式碼複製到 ,並實作函式:" + +#: src/tuples-and-arrays/exercise.md src/borrowing/exercise.md +#: src/unsafe-rust/exercise.md +msgid "// TODO: remove this when you're done with your implementation.\n" +msgstr "// TODO: remove this when you're done with your implementation.\n" + +#: src/tuples-and-arrays/exercise.md src/tuples-and-arrays/solution.md +msgid "//\n" +msgstr "//\n" + +#: src/tuples-and-arrays/exercise.md src/tuples-and-arrays/solution.md +msgid "// <-- the comment makes rustfmt add a newline\n" +msgstr "// <-- the comment makes rustfmt add a newline\n" + +#: src/tuples-and-arrays/exercise.md src/tuples-and-arrays/solution.md +msgid "\"matrix: {:#?}\"" +msgstr "\"matrix: {:#?}\"" + +#: src/tuples-and-arrays/exercise.md src/tuples-and-arrays/solution.md +msgid "\"transposed: {:#?}\"" +msgstr "\"transposed: {:#?}\"" + +#: src/references.md +msgid "[Shared References](./references/shared.md) (10 minutes)" +msgstr "[共用參照](./references/shared.md) (10 分鐘)" + +#: src/references.md +msgid "[Exclusive References](./references/exclusive.md) (10 minutes)" +msgstr "[專屬參照](./references/Exclusive.md) (10 分鐘)" + +#: src/references.md +msgid "[Exercise: Geometry](./references/exercise.md) (15 minutes)" +msgstr "[練習:幾何圖形](./references/exercise.md) (15 分鐘)" + +#: src/references/shared.md +msgid "" +"A reference provides a way to access another value without taking " +"responsibility for the value, and is also called \"borrowing\". Shared " +"references are read-only, and the referenced data cannot change." msgstr "" -"標準程式庫:`String`、`Option` 和 `Result`、`Vec`、`HashMap`、`Rc` 和 `Arc`。" +"所謂參照,是一種可存取另一值而不對該值負責的方法,也稱為「借用 " +"(borrowing)」。共用的參照僅供唯讀,且其參照的資料無法變更。" -#: src/welcome-day-2.md:15 -msgid "Modules: visibility, paths, and filesystem hierarchy." -msgstr "模組:瀏覽權限、路徑和檔案系統階層。" +#: src/references/shared.md +msgid "" +"A shared reference to a type `T` has type `&T`. A reference value is made " +"with the `&` operator. The `*` operator \"dereferences\" a reference, " +"yielding its value." +msgstr "" +"如果是對 `T` 型別的共用參照,就屬於 `&T` 型別。系統會使用 `&` 運算子建立參照" +"值。`*` 運算子則用於將參照「解除參照」,產生參照的值。" -#: src/structs.md:3 +#: src/references/shared.md +msgid "Rust will statically forbid dangling references:" +msgstr "Rust 會以靜態方式禁止迷途參照:" + +#: src/references/shared.md +msgid "" +"A reference is said to \"borrow\" the value it refers to, and this is a good " +"model for students not familiar with pointers: code can use the reference to " +"access the value, but is still \"owned\" by the original variable. The " +"course will get into more detail on ownership in day 3." +msgstr "" +"參照可說是「借用」自身參照的值,對不熟悉指標的學生而言,這是不錯的模型,因為" +"程式碼可以使用參照來存取值,但仍歸原始的變數所「擁有」。本課程將在第 3 天進一" +"步說明擁有權。" + +#: src/references/shared.md +msgid "" +"References are implemented as pointers, and a key advantage is that they can " +"be much smaller than the thing they point to. Students familiar with C or C+" +"+ will recognize references as pointers. Later parts of the course will " +"cover how Rust prevents the memory-safety bugs that come from using raw " +"pointers." +msgstr "" +"參照需以指標的形式實作,主要優點是大小會比指向的目標小得多。熟悉 C 或 C++ 的" +"學生會覺得參照很像指標。在稍後的課程中,我們將介紹 Rust 如何避免使用原始指標" +"導致的記憶體安全錯誤。" + +#: src/references/shared.md +msgid "" +"Rust does not automatically create references for you - the `&` is always " +"required." +msgstr "Rust 不會自動為您建立參照,一律須使用 `&`。" + +#: src/references/shared.md +#, fuzzy +msgid "" +"Rust will auto-dereference in some cases, in particular when invoking " +"methods (try `r.is_ascii()`). There is no need for an `->` operator like in " +"C++." +msgstr "" +"在某些情況下,尤其是在叫用方法時,Rust 會自動解除參照 (請嘗試使用 `ref_x." +"count_ones()`)。" + +#: src/references/shared.md +msgid "" +"In this example, `r` is mutable so that it can be reassigned (`r = &b`). " +"Note that this re-binds `r`, so that it refers to something else. This is " +"different from C++, where assignment to a reference changes the referenced " +"value." +msgstr "" +"這個範例中的 `r` 可變動,因此可以重新指派 (`r = &b`)。請注意,這會重新繫結 " +"`r`,因此會參照其他內容。此方式與 C++ 不同,在 C++ 中,對參照的賦值會變更參照" +"的值。" + +#: src/references/shared.md +msgid "" +"A shared reference does not allow modifying the value it refers to, even if " +"that value was mutable. Try `*r = 'X'`." +msgstr "" +"共用參照不允許修改其參照的值,即使該值可變動也一樣。請嘗試使用 `*r = 'X'`。" + +#: src/references/shared.md +msgid "" +"Rust is tracking the lifetimes of all references to ensure they live long " +"enough. Dangling references cannot occur in safe Rust. `x_axis` would return " +"a reference to `point`, but `point` will be deallocated when the function " +"returns, so this will not compile." +msgstr "" +"Rust 會追蹤所有參照的生命週期,確保其存留時間夠長。在安全的 Rust 中不會發生迷" +"途參照。`x_axis` 會傳回對 `point` 的參照,但在函式傳回時會釋放 `point` ,因此" +"不會編譯。" + +#: src/references/shared.md +msgid "We will talk more about borrowing when we get to ownership." +msgstr "我們會在講到擁有權時進一步探討「借用」。" + +#: src/references/exclusive.md +msgid "" +"Exclusive references, also known as mutable references, allow changing the " +"value they refer to. They have type `&mut T`." +msgstr "" +"專屬參照 (也稱做可變動參照) 允許變更自身參照的值。這類參照屬於 `&mut T` 型" +"別。" + +#: src/references/exclusive.md +msgid "" +"\"Exclusive\" means that only this reference can be used to access the " +"value. No other references (shared or exclusive) can exist at the same time, " +"and the referenced value cannot be accessed while the exclusive reference " +"exists. Try making an `&point.0` or changing `point.0` while `x_coord` is " +"alive." +msgstr "" +"「專屬」表示只有這個參照可用來存取值。任何其他參照 (不論是共用或專屬參照) 都" +"不可以同時存在,此外,在專屬參照存在的情況下,就無法存取參照的值。請嘗試在 " +"`x_coord` 運作時建立 `&point.0` 或變更 `point.0`。" + +#: src/references/exclusive.md +#, fuzzy +msgid "" +"Be sure to note the difference between `let mut x_coord: &i32` and `let " +"x_coord: &mut i32`. The first one represents a shared reference which can be " +"bound to different values, while the second represents an exclusive " +"reference to a mutable value." +msgstr "" +"請務必留意 `let mut ref_x: &i32` 和 `let ref_x: &mut i32` 的差異。前者代表可" +"變動的參照,可綁定至不同的值;後者則代表可變動值的參照。" + +#: src/references/exercise.md +msgid "" +"We will create a few utility functions for 3-dimensional geometry, " +"representing a point as `[f64;3]`. It is up to you to determine the function " +"signatures." +msgstr "" +"我們會建立幾個 3D 幾何圖形的公用函式,將點表示為 `[f64;3]`。函式簽章則由您自" +"行決定。" + +#: src/references/exercise.md +msgid "" +"// Calculate the magnitude of a vector by summing the squares of its " +"coordinates\n" +"// and taking the square root. Use the `sqrt()` method to calculate the " +"square\n" +"// root, like `v.sqrt()`.\n" +msgstr "" +"// Calculate the magnitude of a vector by summing the squares of its " +"coordinates\n" +"// and taking the square root. Use the `sqrt()` method to calculate the " +"square\n" +"// root, like `v.sqrt()`.\n" + +#: src/references/exercise.md +msgid "" +"// Normalize a vector by calculating its magnitude and dividing all of its\n" +"// coordinates by that magnitude.\n" +msgstr "" +"// Normalize a vector by calculating its magnitude and dividing all of its\n" +"// coordinates by that magnitude.\n" + +#: src/references/exercise.md +msgid "// Use the following `main` to test your work.\n" +msgstr "// Use the following `main` to test your work.\n" + +#: src/references/exercise.md src/references/solution.md +msgid "\"Magnitude of a unit vector: {}\"" +msgstr "\"Magnitude of a unit vector: {}\"" + +#: src/references/exercise.md src/references/solution.md +msgid "\"Magnitude of {v:?}: {}\"" +msgstr "\"Magnitude of {v:?}: {}\"" + +#: src/references/exercise.md src/references/solution.md +msgid "\"Magnitude of {v:?} after normalization: {}\"" +msgstr "\"Magnitude of {v:?} after normalization: {}\"" + +#: src/references/solution.md +msgid "/// Calculate the magnitude of the given vector.\n" +msgstr "/// Calculate the magnitude of the given vector.\n" + +#: src/references/solution.md +msgid "" +"/// Change the magnitude of the vector to 1.0 without changing its " +"direction.\n" +msgstr "" +"/// Change the magnitude of the vector to 1.0 without changing its " +"direction.\n" + +#: src/user-defined-types.md +msgid "[Named Structs](./user-defined-types/named-structs.md) (10 minutes)" +msgstr "[已命名的結構體](./user-defined-types/named-structs.md) (10 分鐘)" + +#: src/user-defined-types.md +msgid "[Tuple Structs](./user-defined-types/tuple-structs.md) (10 minutes)" +msgstr "[元組結構體](./user-defined-types/tuple-structs.md) (10 分鐘)" + +#: src/user-defined-types.md +msgid "[Enums](./user-defined-types/enums.md) (5 minutes)" +msgstr "[列舉](./user-defined-types/enums.md) (5 分鐘)" + +#: src/user-defined-types.md +msgid "" +"[Static and Const](./user-defined-types/static-and-const.md) (5 minutes)" +msgstr "[靜態和常數](./user-defined-types/static-and-const.md) (5 分鐘)" + +#: src/user-defined-types.md +msgid "[Type Aliases](./user-defined-types/aliases.md) (2 minutes)" +msgstr "[型別別名](./user-defined-types/aliases.md) (2 分鐘)" + +#: src/user-defined-types.md +msgid "" +"[Exercise: Elevator Events](./user-defined-types/exercise.md) (15 minutes)" +msgstr "[練習:電梯事件](./user-defined-types/exercise.md) (15 分鐘)" + +#: src/user-defined-types.md src/borrowing.md +msgid "This segment should take about 50 minutes" +msgstr "講解這個主題大約需要 50 分鐘" + +#: src/user-defined-types/named-structs.md msgid "Like C and C++, Rust has support for custom structs:" msgstr "與 C 和 C++ 一樣,Rust 支援自訂結構體:" -#: src/structs.md:5 -msgid "" -"```rust,editable\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"\n" -"fn main() {\n" -" let mut peter = Person {\n" -" name: String::from(\"Peter\"),\n" -" age: 27,\n" -" };\n" -" println!(\"{} is {} years old\", peter.name, peter.age);\n" -" \n" -" peter.age = 28;\n" -" println!(\"{} is {} years old\", peter.name, peter.age);\n" -" \n" -" let jackie = Person {\n" -" name: String::from(\"Jackie\"),\n" -" ..peter\n" -" };\n" -" println!(\"{} is {} years old\", jackie.name, jackie.age);\n" -"}\n" -"```" -msgstr "" +#: src/user-defined-types/named-structs.md +msgid "\"{} is {} years old\"" +msgstr "\"{} is {} years old\"" -#: src/structs.md:31 src/enums.md:34 src/enums/sizes.md:29 src/methods.md:30 -#: src/methods/example.md:46 src/pattern-matching.md:25 -#: src/pattern-matching/match-guards.md:22 src/control-flow/blocks.md:42 +#: src/user-defined-types/named-structs.md +#: src/android/interoperability/with-c/bindgen.md +msgid "\"Peter\"" +msgstr "\"Peter\"" + +#: src/user-defined-types/named-structs.md +msgid "\"Avery\"" +msgstr "\"Avery\"" + +#: src/user-defined-types/named-structs.md +msgid "\"Jackie\"" +msgstr "\"Jackie\"" + +#: src/user-defined-types/named-structs.md src/user-defined-types/enums.md +#: src/pattern-matching/match.md src/methods-and-traits/methods.md msgid "Key Points:" msgstr "重點:" -#: src/structs.md:33 +#: src/user-defined-types/named-structs.md msgid "Structs work like in C or C++." msgstr "結構體的運作方式與在 C 或 C++ 中類似。" -#: src/structs.md:34 +#: src/user-defined-types/named-structs.md msgid "Like in C++, and unlike in C, no typedef is needed to define a type." msgstr "不需要 typedef 即可定義型別。這與 C++ 類似,但與 C 不同。" -#: src/structs.md:35 +#: src/user-defined-types/named-structs.md msgid "Unlike in C++, there is no inheritance between structs." msgstr "與 C++ 不同的是,結構體之間沒有繼承關係。" -#: src/structs.md:36 -msgid "" -"Methods are defined in an `impl` block, which we will see in following " -"slides." -msgstr "方法會在 `impl` 區塊中定義,我們將於接下來的投影片說明這點。" - -#: src/structs.md:37 +#: src/user-defined-types/named-structs.md +#, fuzzy msgid "" "This may be a good time to let people know there are different types of " -"structs. " +"structs." msgstr "不妨趁此機會讓學員瞭解還有幾種不同的結構體。" -#: src/structs.md:38 +#: src/user-defined-types/named-structs.md +#, fuzzy msgid "" -"Zero-sized structs `e.g., struct Foo;` might be used when implementing a " +"Zero-sized structs (e.g. `struct Foo;`) might be used when implementing a " "trait on some type but don’t have any data that you want to store in the " -"value itself. " +"value itself." msgstr "" "針對某些型別實作特徵時,可能會使用大小為零的結構體 `e.g., struct Foo;`,但其" "中沒有任何需要儲存在值本身的資料。" -#: src/structs.md:39 +#: src/user-defined-types/named-structs.md msgid "" "The next slide will introduce Tuple structs, used when the field names are " "not important." msgstr "在下一張投影片中,我們會介紹元組結構體,可於欄位名稱不重要時使用。" -#: src/structs.md:40 +#: src/user-defined-types/named-structs.md +#, fuzzy msgid "" -"The syntax `..peter` allows us to copy the majority of the fields from the " +"If you already have variables with the right names, then you can create the " +"struct using a shorthand." +msgstr "如果您已有名稱相同的變數,可以透過簡寫 建立結構體:" + +#: src/user-defined-types/named-structs.md +#, fuzzy +msgid "" +"The syntax `..avery` allows us to copy the majority of the fields from the " "old struct without having to explicitly type it all out. It must always be " "the last element." msgstr "" "`..peter` 語法可讓我們從舊的結構體中複製大部分欄位,而不必明確輸入所有欄位。" "此元素一律須位於最後。" -#: src/structs/tuple-structs.md:3 +#: src/user-defined-types/tuple-structs.md msgid "If the field names are unimportant, you can use a tuple struct:" msgstr "如果欄位名稱不重要,您可以使用元組結構體:" -#: src/structs/tuple-structs.md:5 -msgid "" -"```rust,editable\n" -"struct Point(i32, i32);\n" -"\n" -"fn main() {\n" -" let p = Point(17, 23);\n" -" println!(\"({}, {})\", p.0, p.1);\n" -"}\n" -"```" -msgstr "" +#: src/user-defined-types/tuple-structs.md +msgid "\"({}, {})\"" +msgstr "\"({}, {})\"" -#: src/structs/tuple-structs.md:14 +#: src/user-defined-types/tuple-structs.md msgid "This is often used for single-field wrappers (called newtypes):" msgstr "這通常用於單一欄位的包裝函式 (稱為 newtypes):" -#: src/structs/tuple-structs.md:16 -msgid "" -"```rust,editable,compile_fail\n" -"struct PoundsOfForce(f64);\n" -"struct Newtons(f64);\n" -"\n" -"fn compute_thruster_force() -> PoundsOfForce {\n" -" todo!(\"Ask a rocket scientist at NASA\")\n" -"}\n" -"\n" -"fn set_thruster_force(force: Newtons) {\n" -" // ...\n" -"}\n" -"\n" -"fn main() {\n" -" let force = compute_thruster_force();\n" -" set_thruster_force(force);\n" -"}\n" -"\n" -"```" -msgstr "" +#: src/user-defined-types/tuple-structs.md +msgid "\"Ask a rocket scientist at NASA\"" +msgstr "\"Ask a rocket scientist at NASA\"" -#: src/structs/tuple-structs.md:37 +#: src/user-defined-types/tuple-structs.md +#: src/android/interoperability/cpp/cpp-bridge.md +#: src/bare-metal/microcontrollers/type-state.md +#: src/async/pitfalls/cancellation.md +msgid "// ...\n" +msgstr "// ...\n" + +#: src/user-defined-types/tuple-structs.md msgid "" "Newtypes are a great way to encode additional information about the value in " "a primitive type, for example:" msgstr "" "如要對原始型別中值的額外資訊進行編碼,Newtypes 是絕佳的方式,舉例來說:" -#: src/structs/tuple-structs.md:38 +#: src/user-defined-types/tuple-structs.md msgid "The number is measured in some units: `Newtons` in the example above." msgstr "此數字會採用某些測量單位:在上例中為 `Newtons`。" -#: src/structs/tuple-structs.md:39 +#: src/user-defined-types/tuple-structs.md +#, fuzzy msgid "" "The value passed some validation when it was created, so you no longer have " -"to validate it again at every use: 'PhoneNumber(String)`or`OddNumber(u32)\\`." +"to validate it again at every use: `PhoneNumber(String)` or `OddNumber(u32)`." msgstr "" "此值在建立時已通過某些驗證,因此往後不必在每次使用時再次驗證。例" "如:'PhoneNumber(String)`或`OddNumber(u32)\\` 。" -#: src/structs/tuple-structs.md:40 +#: src/user-defined-types/tuple-structs.md msgid "" "Demonstrate how to add a `f64` value to a `Newtons` type by accessing the " "single field in the newtype." msgstr "" "示範如何透過存取 newtype 中的單一欄位,將 “f64” 值新增至 `Newtons` 類型。" -#: src/structs/tuple-structs.md:41 +#: src/user-defined-types/tuple-structs.md msgid "" "Rust generally doesn’t like inexplicit things, like automatic unwrapping or " "for instance using booleans as integers." msgstr "Rust 通常不太能接受不明確的內容,例如自動展開或使用布林值做為整數。" -#: src/structs/tuple-structs.md:42 -msgid "Operator overloading is discussed on Day 3 (generics). " +#: src/user-defined-types/tuple-structs.md +msgid "Operator overloading is discussed on Day 3 (generics)." +msgstr "運算子超載會在第 3 天 (泛型) 討論。" + +#: src/user-defined-types/tuple-structs.md +msgid "" +"The example is a subtle reference to the [Mars Climate Orbiter](https://en." +"wikipedia.org/wiki/Mars_Climate_Orbiter) failure." msgstr "" +"此範例巧妙地以 [Mars Climate Orbiter](https://en.wikipedia.org/wiki/" +"Mars_Climate_Orbiter) 的失敗經驗做為參照。" -#: src/structs/field-shorthand.md:3 -msgid "" -"If you already have variables with the right names, then you can create the " -"struct using a shorthand:" -msgstr "如果您已有名稱相同的變數,可以透過簡寫 建立結構體:" - -#: src/structs/field-shorthand.md:6 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"\n" -"impl Person {\n" -" fn new(name: String, age: u8) -> Person {\n" -" Person { name, age }\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let peter = Person::new(String::from(\"Peter\"), 27);\n" -" println!(\"{peter:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/structs/field-shorthand.md:27 -msgid "" -"The `new` function could be written using `Self` as a type, as it is " -"interchangeable with the struct type name" -msgstr "" -"您可以將 `Self` 用做型別來編寫 `new` 函式,因為它可和結構體型別名稱互通。" - -#: src/structs/field-shorthand.md:29 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"impl Person {\n" -" fn new(name: String, age: u8) -> Self {\n" -" Self { name, age }\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/structs/field-shorthand.md:41 -msgid "" -"Implement the `Default` trait for the struct. Define some fields and use the " -"default values for the other fields." -msgstr "" -"實作結構體的 `Default` 特徵。請定義部分欄位,並針對其他欄位使用預設值。" - -#: src/structs/field-shorthand.md:43 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"impl Default for Person {\n" -" fn default() -> Person {\n" -" Person {\n" -" name: \"Bot\".to_string(),\n" -" age: 0,\n" -" }\n" -" }\n" -"}\n" -"fn create_default() {\n" -" let tmp = Person {\n" -" ..Default::default()\n" -" };\n" -" let tmp = Person {\n" -" name: \"Sam\".to_string(),\n" -" ..Default::default()\n" -" };\n" -"}\n" -"```" -msgstr "" - -#: src/structs/field-shorthand.md:68 -msgid "Methods are defined in the `impl` block." -msgstr "方法會在 `impl` 區塊中定義。" - -#: src/structs/field-shorthand.md:69 -msgid "" -"Use struct update syntax to define a new structure using `peter`. Note that " -"the variable `peter` will no longer be accessible afterwards." -msgstr "" -"使用結構體更新語法,利用 `peter` 定義新結構。請注意,`peter` 這個變數之後將再" -"也無法存取。" - -#: src/structs/field-shorthand.md:70 -msgid "" -"Use `{:#?}` when printing structs to request the `Debug` representation." -msgstr "輸出結構體時,請使用 `{:#?}` 提出 `Debug` 表示法要求。" - -#: src/enums.md:3 +#: src/user-defined-types/enums.md msgid "" "The `enum` keyword allows the creation of a type which has a few different " "variants:" msgstr "`enum` 關鍵字可建立具有幾個不同變體的型別:" -#: src/enums.md:6 -msgid "" -"```rust,editable\n" -"fn generate_random_number() -> i32 {\n" -" // Implementation based on https://xkcd.com/221/\n" -" 4 // Chosen by fair dice roll. Guaranteed to be random.\n" -"}\n" -"\n" -"#[derive(Debug)]\n" -"enum CoinFlip {\n" -" Heads,\n" -" Tails,\n" -"}\n" -"\n" -"fn flip_coin() -> CoinFlip {\n" -" let random_number = generate_random_number();\n" -" if random_number % 2 == 0 {\n" -" return CoinFlip::Heads;\n" -" } else {\n" -" return CoinFlip::Tails;\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"You got: {:?}\", flip_coin());\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn generate_random_number() -> i32 {\n" -" // Implementation based on https://xkcd.com/221/\n" -" 4 // Chosen by fair dice roll. Guaranteed to be random.\n" -"}\n" -"\n" -"#[derive(Debug)]\n" -"enum CoinFlip {\n" -" Heads,\n" -" Tails,\n" -"}\n" -"\n" -"fn flip_coin() -> CoinFlip {\n" -" let random_number = generate_random_number();\n" -" if random_number % 2 == 0 {\n" -" return CoinFlip::Heads;\n" -" } else {\n" -" return CoinFlip::Tails;\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"You got: {:?}\", flip_coin());\n" -"}\n" -"```" +#: src/user-defined-types/enums.md +msgid "// Simple variant\n" +msgstr "// Simple variant\n" -#: src/enums.md:36 -msgid "Enumerations allow you to collect a set of values under one type" +#: src/user-defined-types/enums.md +msgid "// Tuple variant\n" +msgstr "// Tuple variant\n" + +#: src/user-defined-types/enums.md +msgid "// Struct variant\n" +msgstr "// Struct variant\n" + +#: src/user-defined-types/enums.md +msgid "\"On this turn: {:?}\"" +msgstr "\"On this turn: {:?}\"" + +#: src/user-defined-types/enums.md +#, fuzzy +msgid "Enumerations allow you to collect a set of values under one type." msgstr "列舉可讓您在單一類別中收集一組值。" -#: src/enums.md:37 +#: src/user-defined-types/enums.md msgid "" -"This page offers an enum type `CoinFlip` with two variants `Heads` and " -"`Tail`. You might note the namespace when using variants." +"`Direction` is a type with variants. There are two values of `Direction`: " +"`Direction::Left` and `Direction::Right`." msgstr "" -"本頁面提供列舉類別 `CoinFlip`,以及 `Heads` 和 `Tail` 這兩個變體。您可以在使" -"用變體時記下命名空間。" +"`Direction` 是含變體的型別,有`Direction::Left` 和 `Direction::Right` 這兩個" +"值。" -#: src/enums.md:38 -msgid "This might be a good time to compare Structs and Enums:" +#: src/user-defined-types/enums.md +msgid "" +"`PlayerMove` is a type with three variants. In addition to the payloads, " +"Rust will store a discriminant so that it knows at runtime which variant is " +"in a `PlayerMove` value." +msgstr "" +"`PlayerMove` 是含三種變體的型別。除了酬載之外,Rust 還會儲存判別值,以便在執" +"行階段瞭解哪個變體屬於 `PlayerMove` 值。" + +#: src/user-defined-types/enums.md +#, fuzzy +msgid "This might be a good time to compare structs and enums:" msgstr "這或許是比較結構體和列舉的好時機:" -#: src/enums.md:39 +#: src/user-defined-types/enums.md +#, fuzzy msgid "" "In both, you can have a simple version without fields (unit struct) or one " -"with different types of fields (variant payloads). " +"with different types of fields (variant payloads)." msgstr "" "無論使用何者,都能取得沒有欄位的簡易版本 (單元結構體),或是具有不同欄位型別的" "版本 (變體負載)。" -#: src/enums.md:40 -msgid "In both, associated functions are defined within an `impl` block." -msgstr "無論使用何者,相關函式都會在 `impl` 區塊中定義。" - -#: src/enums.md:41 +#: src/user-defined-types/enums.md +#, fuzzy msgid "" "You could even implement the different variants of an enum with separate " "structs but then they wouldn’t be the same type as they would if they were " -"all defined in an enum. " +"all defined in an enum." msgstr "" "您甚至可以使用獨立的結構體實作列舉的不同變體,但比起在列舉中定義全部變體的情" "況,這麼做會讓變體的型別有所不同。" -#: src/enums/variant-payloads.md:3 +#: src/user-defined-types/enums.md +msgid "Rust uses minimal space to store the discriminant." +msgstr "Rust 會以最少的空間來儲存判別值。" + +#: src/user-defined-types/enums.md +msgid "If necessary, it stores an integer of the smallest required size" +msgstr "如有需要,Rust 會儲存最小所需大小的整數" + +#: src/user-defined-types/enums.md msgid "" -"You can define richer enums where the variants carry data. You can then use " -"the `match` statement to extract the data from each variant:" +"If the allowed variant values do not cover all bit patterns, it will use " +"invalid bit patterns to encode the discriminant (the \"niche " +"optimization\"). For example, `Option<&u8>` stores either a pointer to an " +"integer or `NULL` for the `None` variant." msgstr "" -"您可以定義更豐富的列舉,讓列舉的變體攜帶資料。接著,您可以使用 `match` 陳述" -"式,從各個變體擷取資料:" +"如果允許的變體值未涵蓋所有位元模式,Rust 會使用無效的位元模式來編碼判別值 (即" +"「區位最佳化」)。舉例來說,`Option<&u8>` 可儲存指向整數的指標,也可儲存 " +"`None` 變體適用的 `NULL`。" -#: src/enums/variant-payloads.md:6 -msgid "" -"```rust,editable\n" -"enum WebEvent {\n" -" PageLoad, // Variant without payload\n" -" KeyPress(char), // Tuple struct variant\n" -" Click { x: i64, y: i64 }, // Full struct variant\n" -"}\n" -"\n" -"#[rustfmt::skip]\n" -"fn inspect(event: WebEvent) {\n" -" match event {\n" -" WebEvent::PageLoad => println!(\"page loaded\"),\n" -" WebEvent::KeyPress(c) => println!(\"pressed '{c}'\"),\n" -" WebEvent::Click { x, y } => println!(\"clicked at x={x}, y={y}\"),\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let load = WebEvent::PageLoad;\n" -" let press = WebEvent::KeyPress('x');\n" -" let click = WebEvent::Click { x: 20, y: 80 };\n" -"\n" -" inspect(load);\n" -" inspect(press);\n" -" inspect(click);\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"enum WebEvent {\n" -" PageLoad, // Variant without payload\n" -" KeyPress(char), // Tuple struct variant\n" -" Click { x: i64, y: i64 }, // Full struct variant\n" -"}\n" -"\n" -"#[rustfmt::skip]\n" -"fn inspect(event: WebEvent) {\n" -" match event {\n" -" WebEvent::PageLoad => println!(\"page loaded\"),\n" -" WebEvent::KeyPress(c) => println!(\"pressed '{c}'\"),\n" -" WebEvent::Click { x, y } => println!(\"clicked at x={x}, y={y}\"),\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let load = WebEvent::PageLoad;\n" -" let press = WebEvent::KeyPress('x');\n" -" let click = WebEvent::Click { x: 20, y: 80 };\n" -"\n" -" inspect(load);\n" -" inspect(press);\n" -" inspect(click);\n" -"}\n" -"```" - -#: src/enums/variant-payloads.md:35 -msgid "" -"The values in the enum variants can only be accessed after being pattern " -"matched. The pattern binds references to the fields in the \"match arm\" " -"after the `=>`." -msgstr "" -"只有在與模式配對相符後,才能存取列舉變數中的值。此模式會將參照繫結至 `=>` 後" -"方「配對分支」中的欄位。" - -#: src/enums/variant-payloads.md:36 -msgid "" -"The expression is matched against the patterns from top to bottom. There is " -"no fall-through like in C or C++." -msgstr "" -"系統會從上到下將運算式與模式進行配對。在 Rust 中,不會像在 C 或 C++ 中一樣出" -"現貫穿 (fall-through) 情形。" - -#: src/enums/variant-payloads.md:37 -msgid "" -"The match expression has a value. The value is the last expression in the " -"match arm which was executed." -msgstr "配對運算式具有值。此值是系統執行的配對分支中的最後一個運算式。" - -#: src/enums/variant-payloads.md:38 -msgid "" -"Starting from the top we look for what pattern matches the value then run " -"the code following the arrow. Once we find a match, we stop. " -msgstr "" -"我們會從上方開始尋找符合該值的模式,然後執行箭頭後方的程式碼。一旦發現相符項" -"目,就會停止。" - -#: src/enums/variant-payloads.md:39 -msgid "" -"Demonstrate what happens when the search is inexhaustive. Note the advantage " -"the Rust compiler provides by confirming when all cases are handled. " -msgstr "" -"請示範非窮舉搜尋的情況。請確認系統處理所有案例的時間,指出 Rust 編譯器提供的" -"優勢。" - -#: src/enums/variant-payloads.md:40 -msgid "`match` inspects a hidden discriminant field in the `enum`." -msgstr "`match` 會檢查 `enum` 中隱藏的判別值欄位。" - -#: src/enums/variant-payloads.md:41 -msgid "" -"It is possible to retrieve the discriminant by calling `std::mem::" -"discriminant()`" -msgstr "只要呼叫 `std::mem::discriminant()`,就有可能擷取該判別值。\\`" - -#: src/enums/variant-payloads.md:42 -msgid "" -"This is useful, for example, if implementing `PartialEq` for structs where " -"comparing field values doesn't affect equality." -msgstr "" -"舉例來說,如果在為結構體實作 `PartialEq` 時,比較欄位值不會對相等性造成影響," -"這種做法就很實用。" - -#: src/enums/variant-payloads.md:43 -msgid "" -"`WebEvent::Click { ... }` is not exactly the same as `WebEvent::" -"Click(Click)` with a top level `struct Click { ... }`. The inlined version " -"cannot implement traits, for example." -msgstr "" -"`WebEvent::Click { ... }` 與具有頂層 `struct Click { ... }` 的 `WebEvent::" -"Click(Click)` 並非完全相同。舉例來說,內嵌版本無法實作特徵。" - -#: src/enums/sizes.md:3 -msgid "" -"Rust enums are packed tightly, taking constraints due to alignment into " -"account:" -msgstr "Rust 列舉會緊密封裝,並考量因對齊而造成的限制:" - -#: src/enums/sizes.md:5 -msgid "" -"```rust,editable\n" -"use std::mem::{align_of, size_of};\n" -"\n" -"macro_rules! dbg_size {\n" -" ($t:ty) => {\n" -" println!(\"{}: size {} bytes, align: {} bytes\",\n" -" stringify!($t), size_of::<$t>(), align_of::<$t>());\n" -" };\n" -"}\n" -"\n" -"enum Foo {\n" -" A,\n" -" B,\n" -"}\n" -"\n" -"fn main() {\n" -" dbg_size!(Foo);\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"use std::mem::{align_of, size_of};\n" -"\n" -"macro_rules! dbg_size {\n" -" ($t:ty) => {\n" -" println!(\"{}: size {} bytes, align: {} bytes\",\n" -" stringify!($t), size_of::<$t>(), align_of::<$t>());\n" -" };\n" -"}\n" -"\n" -"enum Foo {\n" -" A,\n" -" B,\n" -"}\n" -"\n" -"fn main() {\n" -" dbg_size!(Foo);\n" -"}\n" -"```" - -#: src/enums/sizes.md:25 -msgid "" -"See the [Rust Reference](https://doc.rust-lang.org/reference/type-layout." -"html)." -msgstr "" -"請參閱 [Rust 參考資料](https://doc.rust-lang.org/reference/type-layout." -"html)。" - -#: src/enums/sizes.md:31 -msgid "" -"Internally Rust is using a field (discriminant) to keep track of the enum " -"variant." -msgstr "在內部,Rust 會使用欄位 (判別值) 追蹤列舉變體。" - -#: src/enums/sizes.md:33 +#: src/user-defined-types/enums.md msgid "" "You can control the discriminant if needed (e.g., for compatibility with C):" msgstr "您可以視需要控制判別值,例如為了與 C 相容:" -#: src/enums/sizes.md:35 -msgid "" -"```rust,editable\n" -"#[repr(u32)]\n" -"enum Bar {\n" -" A, // 0\n" -" B = 10000,\n" -" C, // 10001\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"A: {}\", Bar::A as u32);\n" -" println!(\"B: {}\", Bar::B as u32);\n" -" println!(\"C: {}\", Bar::C as u32);\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"#[repr(u32)]\n" -"enum Bar {\n" -" A, // 0\n" -" B = 10000,\n" -" C, // 10001\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"A: {}\", Bar::A as u32);\n" -" println!(\"B: {}\", Bar::B as u32);\n" -" println!(\"C: {}\", Bar::C as u32);\n" -"}\n" -"```" - -#: src/enums/sizes.md:50 +#: src/user-defined-types/enums.md msgid "" "Without `repr`, the discriminant type takes 2 bytes, because 10001 fits 2 " "bytes." msgstr "" "如果沒有 `repr`,判別值型別會需要 2 個位元組,因為 10001 適合 2 個位元組。" -#: src/enums/sizes.md:54 -msgid "Try out other types such as" -msgstr "請嘗試其他型別,例如以下項目:" +#: src/user-defined-types/enums.md src/user-defined-types/static-and-const.md +#: src/memory-management/review.md src/memory-management/move.md +#: src/smart-pointers/box.md src/borrowing/shared.md +msgid "More to Explore" +msgstr "探索更多內容" -#: src/enums/sizes.md:56 -msgid "`dbg_size!(bool)`: size 1 bytes, align: 1 bytes," -msgstr "`dbg_size!(bool)`:大小為 1 個位元組,對齊:1 個位元組。" - -#: src/enums/sizes.md:57 +#: src/user-defined-types/enums.md msgid "" -"`dbg_size!(Option)`: size 1 bytes, align: 1 bytes (niche optimization, " -"see below)," -msgstr "" -"`dbg_size!(Option)`:大小為 1 個位元組,對齊:1 個位元組 (區位最佳化," -"請見下文)。" +"Rust has several optimizations it can employ to make enums take up less " +"space." +msgstr "Rust 支援多種最佳化做法,可用於縮減列舉占用的空間。" -#: src/enums/sizes.md:58 -msgid "`dbg_size!(&i32)`: size 8 bytes, align: 8 bytes (on a 64-bit machine)," -msgstr "" -"`dbg_size!(&i32)`:大小為 8 個位元組,對齊:8 個位元組 (在 64 位元機器上)。" - -#: src/enums/sizes.md:59 -msgid "" -"`dbg_size!(Option<&i32>)`: size 8 bytes, align: 8 bytes (null pointer " -"optimization, see below)." -msgstr "" -"`dbg_size!(Option<&i32>)`:大小為 8 個位元組,對齊:8 個位元組 (空值指標最佳" -"化,請見下文)。" - -#: src/enums/sizes.md:61 -msgid "" -"Niche optimization: Rust will merge use unused bit patterns for the enum " -"discriminant." -msgstr "區位最佳化:Rust 會為列舉判別值合併未使用的位元模式。" - -#: src/enums/sizes.md:64 +#: src/user-defined-types/enums.md msgid "" "Null pointer optimization: For [some types](https://doc.rust-lang.org/std/" "option/#representation), Rust guarantees that `size_of::()` equals " @@ -6380,7 +4586,7 @@ msgstr "" "空值指標最佳化:針對[部分型別](https://doc.rust-lang.org/std/option/" "#representation),Rust 保證 `size_of::()` 等於 `size_of::>()`." -#: src/enums/sizes.md:68 +#: src/user-defined-types/enums.md msgid "" "Example code if you want to show how the bitwise representation _may_ look " "like in practice. It's important to note that the compiler provides no " @@ -6389,690 +4595,505 @@ msgstr "" "如果想示範位元表示法實際運作時「可能」的樣子,可以使用下列範例程式碼。請務必" "注意,編譯器並無對這個表示法提供保證,因此這完全不安全。" -#: src/enums/sizes.md:71 +#: src/user-defined-types/static-and-const.md +#, fuzzy msgid "" -"```rust,editable\n" -"use std::mem::transmute;\n" -"\n" -"macro_rules! dbg_bits {\n" -" ($e:expr, $bit_type:ty) => {\n" -" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " -"$bit_type>($e));\n" -" };\n" -"}\n" -"\n" -"fn main() {\n" -" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" -" // representation of types.\n" -" unsafe {\n" -" println!(\"Bitwise representation of bool\");\n" -" dbg_bits!(false, u8);\n" -" dbg_bits!(true, u8);\n" -"\n" -" println!(\"Bitwise representation of Option\");\n" -" dbg_bits!(None::, u8);\n" -" dbg_bits!(Some(false), u8);\n" -" dbg_bits!(Some(true), u8);\n" -"\n" -" println!(\"Bitwise representation of Option>\");\n" -" dbg_bits!(Some(Some(false)), u8);\n" -" dbg_bits!(Some(Some(true)), u8);\n" -" dbg_bits!(Some(None::), u8);\n" -" dbg_bits!(None::>, u8);\n" -"\n" -" println!(\"Bitwise representation of Option<&i32>\");\n" -" dbg_bits!(None::<&i32>, usize);\n" -" dbg_bits!(Some(&0i32), usize);\n" -" }\n" -"}\n" -"```" +"Static and constant variables are two different ways to create globally-" +"scoped values that cannot be moved or reallocated during the execution of " +"the program." msgstr "" -"```rust,editable\n" -"use std::mem::transmute;\n" -"\n" -"macro_rules! dbg_bits {\n" -" ($e:expr, $bit_type:ty) => {\n" -" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " -"$bit_type>($e));\n" -" };\n" -"}\n" -"\n" -"fn main() {\n" -" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" -" // representation of types.\n" -" unsafe {\n" -" println!(\"Bitwise representation of bool\");\n" -" dbg_bits!(false, u8);\n" -" dbg_bits!(true, u8);\n" -"\n" -" println!(\"Bitwise representation of Option\");\n" -" dbg_bits!(None::, u8);\n" -" dbg_bits!(Some(false), u8);\n" -" dbg_bits!(Some(true), u8);\n" -"\n" -" println!(\"Bitwise representation of Option>\");\n" -" dbg_bits!(Some(Some(false)), u8);\n" -" dbg_bits!(Some(Some(true)), u8);\n" -" dbg_bits!(Some(None::), u8);\n" -" dbg_bits!(None::>, u8);\n" -"\n" -" println!(\"Bitwise representation of Option<&i32>\");\n" -" dbg_bits!(None::<&i32>, usize);\n" -" dbg_bits!(Some(&0i32), usize);\n" -" }\n" -"}\n" -"```" +"靜態和常數變數是建立全域範圍值的兩種不同方式,這個值無法在程式執行期間移動或" +"重新分配。" -#: src/enums/sizes.md:106 +#: src/user-defined-types/static-and-const.md +msgid "`const`" +msgstr "`const`" + +#: src/user-defined-types/static-and-const.md msgid "" -"More complex example if you want to discuss what happens when we chain more " -"than 256 `Option`s together." +"Constant variables are evaluated at compile time and their values are " +"inlined wherever they are used:" +msgstr "常數變數會在編譯期間評估,且無論用於何處,其值都會內嵌:" + +#: src/user-defined-types/static-and-const.md +msgid "" +"According to the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" +"vs-static.html) these are inlined upon use." msgstr "" -"如果想討論將超過 256 個 `Option` 鏈結在一起的情況,可以使用下列更複雜的範例。" +"根據《[Rust RFC 手冊](https://rust-lang.github.io/rfcs/0246-const-vs-static." +"html)》所述,這類值會在使用時內嵌。" -#: src/enums/sizes.md:108 +#: src/user-defined-types/static-and-const.md msgid "" -"```rust,editable\n" -"#![recursion_limit = \"1000\"]\n" -"\n" -"use std::mem::transmute;\n" -"\n" -"macro_rules! dbg_bits {\n" -" ($e:expr, $bit_type:ty) => {\n" -" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " -"$bit_type>($e));\n" -" };\n" -"}\n" -"\n" -"// Macro to wrap a value in 2^n Some() where n is the number of \"@\" " -"signs.\n" -"// Increasing the recursion limit is required to evaluate this macro.\n" -"macro_rules! many_options {\n" -" ($value:expr) => { Some($value) };\n" -" ($value:expr, @) => {\n" -" Some(Some($value))\n" -" };\n" -" ($value:expr, @ $($more:tt)+) => {\n" -" many_options!(many_options!($value, $($more)+), $($more)+)\n" -" };\n" -"}\n" -"\n" -"fn main() {\n" -" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" -" // representation of types.\n" -" unsafe {\n" -" assert_eq!(many_options!(false), Some(false));\n" -" assert_eq!(many_options!(false, @), Some(Some(false)));\n" -" assert_eq!(many_options!(false, @@), " -"Some(Some(Some(Some(false)))));\n" -"\n" -" println!(\"Bitwise representation of a chain of 128 Option's.\");\n" -" dbg_bits!(many_options!(false, @@@@@@@), u8);\n" -" dbg_bits!(many_options!(true, @@@@@@@), u8);\n" -"\n" -" println!(\"Bitwise representation of a chain of 256 Option's.\");\n" -" dbg_bits!(many_options!(false, @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(true, @@@@@@@@), u16);\n" -"\n" -" println!(\"Bitwise representation of a chain of 257 Option's.\");\n" -" dbg_bits!(many_options!(Some(false), @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(Some(true), @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(None::, @@@@@@@@), u16);\n" -" }\n" -"}\n" -"```" +"Only functions marked `const` can be called at compile time to generate " +"`const` values. `const` functions can however be called at runtime." msgstr "" -"```rust,editable\n" -"#![recursion_limit = \"1000\"]\n" -"\n" -"use std::mem::transmute;\n" -"\n" -"macro_rules! dbg_bits {\n" -" ($e:expr, $bit_type:ty) => {\n" -" println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " -"$bit_type>($e));\n" -" };\n" -"}\n" -"\n" -"// 在 2^n Some() 中包裝值的巨集,n 為「@」符號的數字。\n" -"// 評估此巨集時,必須提高遞迴限制。\n" -"macro_rules! many_options {\n" -" ($value:expr) => { Some($value) };\n" -" ($value:expr, @) => {\n" -" Some(Some($value))\n" -" };\n" -" ($value:expr, @ $($more:tt)+) => {\n" -" many_options!(many_options!($value, $($more)+), $($more)+)\n" -" };\n" -"}\n" -"\n" -"fn main() {\n" -" // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" -" // representation of types.\n" -" unsafe {\n" -" assert_eq!(many_options!(false), Some(false));\n" -" assert_eq!(many_options!(false, @), Some(Some(false)));\n" -" assert_eq!(many_options!(false, @@), " -"Some(Some(Some(Some(false)))));\n" -"\n" -" println!(\"Bitwise representation of a chain of 128 Option's.\");\n" -" dbg_bits!(many_options!(false, @@@@@@@), u8);\n" -" dbg_bits!(many_options!(true, @@@@@@@), u8);\n" -"\n" -" println!(\"Bitwise representation of a chain of 256 Option's.\");\n" -" dbg_bits!(many_options!(false, @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(true, @@@@@@@@), u16);\n" -"\n" -" println!(\"Bitwise representation of a chain of 257 Option's.\");\n" -" dbg_bits!(many_options!(Some(false), @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(Some(true), @@@@@@@@), u16);\n" -" dbg_bits!(many_options!(None::, @@@@@@@@), u16);\n" -" }\n" -"}\n" -"```" +"您只能在編譯期間呼叫標示為 `const` 的函式,以便產生 `const` 值,但可以在執行" +"階段呼叫 `const` 函式。" -#: src/methods.md:3 +#: src/user-defined-types/static-and-const.md +msgid "`static`" +msgstr "`static`" + +#: src/user-defined-types/static-and-const.md msgid "" -"Rust allows you to associate functions with your new types. You do this with " -"an `impl` block:" +"Static variables will live during the whole execution of the program, and " +"therefore will not move:" +msgstr "靜態變數會在程式的整個執行過程中持續運作,因此不會移動:" + +#: src/user-defined-types/static-and-const.md +#, fuzzy +msgid "\"Welcome to RustOS 3.14\"" +msgstr "歡迎參加第 1 天課程" + +#: src/user-defined-types/static-and-const.md +msgid "\"{BANNER}\"" +msgstr "\"{BANNER}\"" + +#: src/user-defined-types/static-and-const.md +#, fuzzy +msgid "" +"As noted in the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" +"vs-static.html), these are not inlined upon use and have an actual " +"associated memory location. This is useful for unsafe and embedded code, and " +"the variable lives through the entirety of the program execution. When a " +"globally-scoped value does not have a reason to need object identity, " +"`const` is generally preferred." msgstr "" -"Rust 可讓您將函式與新型別建立關聯。您可以使用 `impl` 區塊來執行這項操作:" +"如《[Rust RFC 手冊](https://rust-lang.github.io/rfcs/0246-const-vs-static." +"html)》所述,這類值在使用時不會內嵌,且具備實際相關聯的記憶體位置。這對不安全" +"和嵌入的程式碼很有幫助,且變數在程式執行全程都會持續運作。當全域範圍值沒有需" +"要物件識別子的理由時,通常首選會是使用 `const`。" -#: src/methods.md:6 +#: src/user-defined-types/static-and-const.md +msgid "Mention that `const` behaves semantically similar to C++'s `constexpr`." +msgstr "別忘了提到 `const` 的行為在語意上與 C++ 的 `constexpr` 相似。" + +#: src/user-defined-types/static-and-const.md msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Person {\n" -" name: String,\n" -" age: u8,\n" -"}\n" -"\n" -"impl Person {\n" -" fn say_hello(&self) {\n" -" println!(\"Hello, my name is {}\", self.name);\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let peter = Person {\n" -" name: String::from(\"Peter\"),\n" -" age: 27,\n" -" };\n" -" peter.say_hello();\n" -"}\n" -"```" +"`static`, on the other hand, is much more similar to a `const` or mutable " +"global variable in C++." +msgstr "另一方面,`static` 則更類似於 C++ 中的 `const` 或可變動的全域變數。" + +#: src/user-defined-types/static-and-const.md +msgid "" +"`static` provides object identity: an address in memory and state as " +"required by types with interior mutability such as `Mutex`." msgstr "" +"`static` 提供物件識別子,也就是記憶體中的位址,和具有內部可變動性型別 (例如 " +"`Mutex`) 所需的狀態。" -#: src/methods.md:31 -msgid "It can be helpful to introduce methods by comparing them to functions." -msgstr "導入方法時,若將方法比做函式,會很有幫助。" - -#: src/methods.md:32 +#: src/user-defined-types/static-and-const.md msgid "" -"Methods are called on an instance of a type (such as a struct or enum), the " -"first parameter represents the instance as `self`." +"It isn't super common that one would need a runtime evaluated constant, but " +"it is helpful and safer than using a static." msgstr "" -"系統會在型別的執行個體 (例如結構體或列舉) 上呼叫方法,第一個參數以 `self` 代" -"表執行個體。" +"需要在執行階段評估常數的情況雖不常見,但這會比使用靜態項目更有用且安全。" -#: src/methods.md:33 +#: src/user-defined-types/static-and-const.md +msgid "Properties table:" +msgstr "屬性表:" + +#: src/user-defined-types/static-and-const.md +#: src/chromium/adding-third-party-crates.md +msgid "Property" +msgstr "資源" + +#: src/user-defined-types/static-and-const.md +msgid "Static" +msgstr "靜態" + +#: src/user-defined-types/static-and-const.md +msgid "Constant" +msgstr "常數" + +#: src/user-defined-types/static-and-const.md +msgid "Has an address in memory" +msgstr "具備記憶體中的位址" + +#: src/user-defined-types/static-and-const.md +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Yes" +msgstr "是" + +#: src/user-defined-types/static-and-const.md +msgid "No (inlined)" +msgstr "否 (已內嵌)" + +#: src/user-defined-types/static-and-const.md +msgid "Lives for the entire duration of the program" +msgstr "在整個程式執行期間持續存在" + +#: src/user-defined-types/static-and-const.md +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "No" +msgstr "否" + +#: src/user-defined-types/static-and-const.md +msgid "Can be mutable" +msgstr "可變動" + +#: src/user-defined-types/static-and-const.md +msgid "Yes (unsafe)" +msgstr "是 (不安全)" + +#: src/user-defined-types/static-and-const.md +#, fuzzy +msgid "Evaluated at compile time" +msgstr "是 (已在編譯時初始化)" + +#: src/user-defined-types/static-and-const.md +msgid "Yes (initialised at compile time)" +msgstr "是 (已在編譯時初始化)" + +#: src/user-defined-types/static-and-const.md +msgid "Inlined wherever it is used" +msgstr "無論在何處使用都會內嵌" + +#: src/user-defined-types/static-and-const.md +#, fuzzy msgid "" -"Developers may choose to use methods to take advantage of method receiver " -"syntax and to help keep them more organized. By using methods we can keep " -"all the implementation code in one predictable place." +"Because `static` variables are accessible from any thread, they must be " +"`Sync`. Interior mutability is possible through a [`Mutex`](https://doc.rust-" +"lang.org/std/sync/struct.Mutex.html), atomic or similar." msgstr "" -"開發人員可以選擇透過方法來充分利用方法接收器語法,以更有條理的方式進行整理。" -"藉由使用方法,我們可以將所有實作程式碼存放在可預測的位置。" +"由於 `static` 變數可從任何執行緒存取,因此必須是 `Sync`。內部可變動性則可透過" +"原子或類似的 [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) " +"實現。也可能有可變動的靜態項目,但這些需要手動同步,因此每當存取這類項目時就" +"需要動用 `unsafe` 程式碼。我們會在「不安全的 Rust」章節中探討[可變動的靜態項" +"目](../unsafe/mutable-static-variables.md)。" -#: src/methods.md:34 -msgid "Point out the use of the keyword `self`, a method receiver. " +#: src/user-defined-types/static-and-const.md +#, fuzzy +msgid "Thread-local data can be created with the macro `std::thread_local`." +msgstr "您可以使用 `std::thread_local` 巨集來建立 `thread_local` 資料。" + +#: src/user-defined-types/aliases.md +msgid "" +"A type alias creates a name for another type. The two types can be used " +"interchangeably." +msgstr "型別別名會為另一型別建立名稱。這兩種型別可以交替使用。" + +#: src/user-defined-types/aliases.md +msgid "// Aliases are more useful with long, complex types:\n" +msgstr "// Aliases are more useful with long, complex types:\n" + +#: src/user-defined-types/aliases.md +msgid "C programmers will recognize this as similar to a `typedef`." +msgstr "別名在 C 語言的程式設計師眼中類似於 `typedef`。" + +#: src/user-defined-types/exercise.md +msgid "" +"We will create a data structure to represent an event in an elevator control " +"system. It is up to you to define the types and functions to construct " +"various events. Use `#[derive(Debug)]` to allow the types to be formatted " +"with `{:?}`." msgstr "" +"我們會建立資料結構,用來代表電梯控制系統中的事件。您可以自行定義類型和函式," +"建構各種事件。請使用 `#[derive(Debug)]` 來允許型別採用 `{:?}` 的格式。" -#: src/methods.md:35 +#: src/user-defined-types/exercise.md msgid "" -"Show that it is an abbreviated term for `self:&Self` and perhaps show how " -"the struct name could also be used. " +"This exercise only requires creating and populating data structures so that " +"`main` runs without errors. The next part of the course will cover getting " +"data out of these structures." msgstr "" +"這項練習只需建立及填入資料結構,`main` 就能在不發生錯誤的情況下執行。本課程的" +"下一部分將介紹如何從這些結構中取得資料。" -#: src/methods.md:36 +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md msgid "" -"Explain that `Self` is a type alias for the type the `impl` block is in and " -"can be used elsewhere in the block." -msgstr "講解 `Self` 是 `impl` 區塊所屬型別的型別別名,可用於該區塊的其他位置。" - -#: src/methods.md:37 -msgid "" -"Note how `self` is used like other structs and dot notation can be used to " -"refer to individual fields." +"/// An event in the elevator system that the controller must react to.\n" msgstr "" -"提醒學員如何以類似於其他結構體的方式來使用 `self`,並指出點標記法可用來參照個" -"別欄位," +"/// An event in the elevator system that the controller must react to.\n" -#: src/methods.md:38 +#: src/user-defined-types/exercise.md +msgid "// TODO: add required variants\n" +msgstr "// TODO: add required variants\n" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "/// A direction of travel.\n" +msgstr "/// A direction of travel.\n" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "/// The car has arrived on the given floor.\n" +msgstr "/// The car has arrived on the given floor.\n" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "/// The car doors have opened.\n" +msgstr "/// The car doors have opened.\n" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "/// The car doors have closed.\n" +msgstr "/// The car doors have closed.\n" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md msgid "" -"This might be a good time to demonstrate how the `&self` differs from `self` " -"by modifying the code and trying to run say_hello twice." +"/// A directional button was pressed in an elevator lobby on the given " +"floor.\n" msgstr "" -"這可能是示範 `&self` 和 `self` 差異的好時機,您只要修改程式碼並嘗試執行 " -"say_hello 兩次即可。" +"/// A directional button was pressed in an elevator lobby on the given " +"floor.\n" -#: src/methods.md:39 -msgid "We describe the distinction between method receivers next." -msgstr "接下來我們將說明方法接收器之間的差異。" +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "/// A floor button was pressed in the elevator car.\n" +msgstr "/// A floor button was pressed in the elevator car.\n" -#: src/methods/receiver.md:3 +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "\"A ground floor passenger has pressed the up button: {:?}\"" +msgstr "\"A ground floor passenger has pressed the up button: {:?}\"" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "\"The car has arrived on the ground floor: {:?}\"" +msgstr "\"The car has arrived on the ground floor: {:?}\"" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "\"The car door opened: {:?}\"" +msgstr "\"The car door opened: {:?}\"" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "\"A passenger has pressed the 3rd floor button: {:?}\"" +msgstr "\"A passenger has pressed the 3rd floor button: {:?}\"" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "\"The car door closed: {:?}\"" +msgstr "\"The car door closed: {:?}\"" + +#: src/user-defined-types/exercise.md src/user-defined-types/solution.md +msgid "\"The car has arrived on the 3rd floor: {:?}\"" +msgstr "\"The car has arrived on the 3rd floor: {:?}\"" + +#: src/user-defined-types/solution.md +msgid "/// A button was pressed.\n" +msgstr "/// A button was pressed.\n" + +#: src/user-defined-types/solution.md +msgid "/// The car has arrived at the given floor.\n" +msgstr "/// The car has arrived at the given floor.\n" + +#: src/user-defined-types/solution.md +msgid "/// The car's doors have opened.\n" +msgstr "/// The car's doors have opened.\n" + +#: src/user-defined-types/solution.md +msgid "/// The car's doors have closed.\n" +msgstr "/// The car's doors have closed.\n" + +#: src/user-defined-types/solution.md +msgid "/// A floor is represented as an integer.\n" +msgstr "/// A floor is represented as an integer.\n" + +#: src/user-defined-types/solution.md +msgid "/// A user-accessible button.\n" +msgstr "/// A user-accessible button.\n" + +#: src/user-defined-types/solution.md +msgid "/// A button in the elevator lobby on the given floor.\n" +msgstr "/// A button in the elevator lobby on the given floor.\n" + +#: src/user-defined-types/solution.md +msgid "/// A floor button within the car.\n" +msgstr "/// A floor button within the car.\n" + +#: src/welcome-day-2.md +msgid "Welcome to Day 2" +msgstr "歡迎參加第 2 天課程" + +#: src/welcome-day-2.md +#, fuzzy msgid "" -"The `&self` above indicates that the method borrows the object immutably. " -"There are other possible receivers for a method:" -msgstr "" -"上述的 `&self` 表示方法會以不可變的方式借用物件。以下是其他可能的方法接收器:" +"Now that we have seen a fair amount of Rust, today will focus on Rust's type " +"system:" +msgstr "您目前對 Rust 已有相當程度的認識,接下來我們將繼續講解以下概念:" -#: src/methods/receiver.md:6 +#: src/welcome-day-2.md +#, fuzzy +msgid "Pattern matching: extracting data from structures." +msgstr "模式配對:解構列舉、結構和陣列。" + +#: src/welcome-day-2.md +msgid "Methods: associating functions with types." +msgstr "方法:將函式與型別建立關聯。" + +#: src/welcome-day-2.md +msgid "Traits: behaviors shared by multiple types." +msgstr "特徵:由多種型別共用的行為。" + +#: src/welcome-day-2.md +msgid "Generics: parameterizing types on other types." +msgstr "泛型:在其他型別上將型別參數化。" + +#: src/welcome-day-2.md msgid "" -"`&self`: borrows the object from the caller using a shared and immutable " -"reference. The object can be used again afterwards." -msgstr "" -"`&self`:使用共用且不可變動的參照,從呼叫端借用物件。之後可以再次使用該物件。" +"Standard library types and traits: a tour of Rust's rich standard library." +msgstr "標準程式庫的型別和特徵:一覽 Rust 豐富的標準程式庫。" -#: src/methods/receiver.md:8 +#: src/welcome-day-2.md +msgid "[Welcome](./welcome-day-2.md) (3 minutes)" +msgstr "[歡迎](./welcome-day-2.md) (3 分鐘)" + +#: src/welcome-day-2.md +#, fuzzy +msgid "[Pattern Matching](./pattern-matching.md) (1 hour)" +msgstr "[模式配對](./pattern-matching.md) (10 分鐘)" + +#: src/welcome-day-2.md +msgid "[Methods and Traits](./methods-and-traits.md) (45 minutes)" +msgstr "[方法和特徵](./methods-and-traits.md) (45 分鐘)" + +#: src/welcome-day-2.md +msgid "[Generics](./generics.md) (40 minutes)" +msgstr "[泛型](./generics.md) (40 分鐘)" + +#: src/welcome-day-2.md msgid "" -"`&mut self`: borrows the object from the caller using a unique and mutable " -"reference. The object can be used again afterwards." -msgstr "" -"`&mut self`:使用不重複且可變動的參照,從呼叫端借用物件。之後可以再次使用該物" -"件。" +"Including 10 minute breaks, this session should take about 2 hours and 50 " +"minutes" +msgstr "講解這個主題大約需要 2 小時 50 分鐘" -#: src/methods/receiver.md:10 +#: src/pattern-matching.md +#, fuzzy +msgid "[Matching Values](./pattern-matching/match.md) (10 minutes)" +msgstr "[配對](./pattern-matching/match.md) (10 分鐘)" + +#: src/pattern-matching.md +msgid "[Destructuring](./pattern-matching/destructuring.md) (10 minutes)" +msgstr "[解構](./pattern-matching/destructuring.md) (10 分鐘)" + +#: src/pattern-matching.md +msgid "[Let Control Flow](./pattern-matching/let-control-flow.md) (10 minutes)" +msgstr "[Let 控制流程](./pattern-matching/let-control-flow.md) (10 分鐘)" + +#: src/pattern-matching.md msgid "" -"`self`: takes ownership of the object and moves it away from the caller. The " -"method becomes the owner of the object. The object will be dropped " -"(deallocated) when the method returns, unless its ownership is explicitly " -"transmitted. Complete ownership does not automatically mean mutability." -msgstr "" -"`self`:取得物件擁有權,並將其移出呼叫端。方法會成為物件的擁有者。系統會在方" -"法傳回時捨棄物件 (取消分配),但如果其擁有權已明確傳送的情況例外。具備完整擁有" -"權,不自動等同於具備可變動性。" +"[Exercise: Expression Evaluation](./pattern-matching/exercise.md) (30 " +"minutes)" +msgstr "[練習:運算式求值](./pattern-matching/exercise.md) (30 分鐘)" -#: src/methods/receiver.md:14 -msgid "`mut self`: same as above, but the method can mutate the object. " -msgstr "`mut self`:同上,但方法可以變動物件。" +#: src/pattern-matching.md src/memory-management.md +msgid "This segment should take about 1 hour" +msgstr "講解這個主題大約需要 1 小時" -#: src/methods/receiver.md:15 +#: src/pattern-matching/match.md +#, fuzzy msgid "" -"No receiver: this becomes a static method on the struct. Typically used to " -"create constructors which are called `new` by convention." -msgstr "" -"沒有接收器:這會成為結構體上的靜態方法,通常用於建立依慣例稱為 `new` 的建構函" -"式。" - -#: src/methods/receiver.md:18 -msgid "" -"Beyond variants on `self`, there are also [special wrapper types](https://" -"doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be " -"receiver types, such as `Box`." -msgstr "" -"除了 `self` 的變體以外,您還可以使用[特殊的包裝函式型別](https://doc.rust-" -"lang.org/reference/special-types-and-traits.html)做為接收器型別,例如 " -"`Box`。" - -#: src/methods/receiver.md:24 -msgid "" -"Consider emphasizing \"shared and immutable\" and \"unique and mutable\". " -"These constraints always come together in Rust due to borrow checker rules, " -"and `self` is no exception. It isn't possible to reference a struct from " -"multiple locations and call a mutating (`&mut self`) method on it." -msgstr "" -"建議您強調「共用且不可變動」,以及「不重複且可變動」這兩個概念。由於借用檢查" -"器規則的關係,這些限制在 Rust 中一律會一起出現,而 `self` 也不例外。您無法從" -"多個位置參照結構體,並對其呼叫變異 (`&mut self`) 方法。" - -#: src/methods/example.md:3 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Race {\n" -" name: String,\n" -" laps: Vec,\n" -"}\n" -"\n" -"impl Race {\n" -" fn new(name: &str) -> Race { // No receiver, a static method\n" -" Race { name: String::from(name), laps: Vec::new() }\n" -" }\n" -"\n" -" fn add_lap(&mut self, lap: i32) { // Exclusive borrowed read-write " -"access to self\n" -" self.laps.push(lap);\n" -" }\n" -"\n" -" fn print_laps(&self) { // Shared and read-only borrowed access to self\n" -" println!(\"Recorded {} laps for {}:\", self.laps.len(), self.name);\n" -" for (idx, lap) in self.laps.iter().enumerate() {\n" -" println!(\"Lap {idx}: {lap} sec\");\n" -" }\n" -" }\n" -"\n" -" fn finish(self) { // Exclusive ownership of self\n" -" let total = self.laps.iter().sum::();\n" -" println!(\"Race {} is finished, total lap time: {}\", self.name, " -"total);\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let mut race = Race::new(\"Monaco Grand Prix\");\n" -" race.add_lap(70);\n" -" race.add_lap(68);\n" -" race.print_laps();\n" -" race.add_lap(71);\n" -" race.print_laps();\n" -" race.finish();\n" -" // race.add_lap(42);\n" -"}\n" -"```" -msgstr "" - -#: src/methods/example.md:47 -msgid "All four methods here use a different method receiver." -msgstr "這裡的四個方法都使用不同的方法接收器。" - -#: src/methods/example.md:48 -msgid "" -"You can point out how that changes what the function can do with the " -"variable values and if/how it can be used again in `main`." -msgstr "" -"您可以指出這會如何變更函式能對變數值執行的動作,以及可否/如何在 `main` 中再次" -"使用該函式。" - -#: src/methods/example.md:49 -msgid "" -"You can showcase the error that appears when trying to call `finish` twice." -msgstr "您可以演示嘗試呼叫 `finish` 兩次時會出現什麼錯誤。" - -#: src/methods/example.md:50 -msgid "" -"Note that although the method receivers are different, the non-static " -"functions are called the same way in the main body. Rust enables automatic " -"referencing and dereferencing when calling methods. Rust automatically adds " -"in the `&`, `*`, `muts` so that that object matches the method signature." -msgstr "" -"請注意,雖然方法接收器不同,但主體中非靜態函式的呼叫方式相同。Rust 會在呼叫方" -"法時啟用自動參照和取消參照功能,並自動加入 `&`、`*`、`muts`,讓該物件與方法簽" -"章相符。" - -#: src/methods/example.md:51 -msgid "" -"You might point out that `print_laps` is using a vector that is iterated " -"over. We describe vectors in more detail in the afternoon. " -msgstr "" -"您或許可以指出 `print_laps` 使用了不斷疊代的向量。我們會在下午詳細介紹向量。" - -#: src/pattern-matching.md:3 -msgid "" -"The `match` keyword let you match a value against one or more _patterns_. " +"The `match` keyword lets you match a value against one or more _patterns_. " "The comparisons are done from top to bottom and the first match wins." msgstr "" "您可以使用 `match` 關鍵字,將值與一或多個「模式」配對。系統會從最上方往下依序" "比對,並套用第一個比對成功的模式。" -#: src/pattern-matching.md:6 +#: src/pattern-matching/match.md msgid "The patterns can be simple values, similarly to `switch` in C and C++:" msgstr "模式可以是簡單的值,類似 C 和 C++ 中的 `switch`:" -#: src/pattern-matching.md:8 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let input = 'x';\n" -"\n" -" match input {\n" -" 'q' => println!(\"Quitting\"),\n" -" 'a' | 's' | 'w' | 'd' => println!(\"Moving around\"),\n" -" '0'..='9' => println!(\"Number input\"),\n" -" _ => println!(\"Something else\"),\n" -" }\n" -"}\n" -"```" +#: src/pattern-matching/match.md +msgid "'x'" +msgstr "'x'" + +#: src/pattern-matching/match.md +msgid "'q'" +msgstr "'q'" + +#: src/pattern-matching/match.md +msgid "\"Quitting\"" msgstr "" -#: src/pattern-matching.md:21 -msgid "The `_` pattern is a wildcard pattern which matches any value." -msgstr "`_` 模式是可與任何值配對的萬用字元模式。" +#: src/pattern-matching/match.md src/std-traits/solution.md +#: src/error-handling/exercise.md src/error-handling/solution.md +#, fuzzy +msgid "'a'" +msgstr "'a'" -#: src/pattern-matching.md:26 +#: src/pattern-matching/match.md +#, fuzzy +msgid "'s'" +msgstr "'s'" + +#: src/pattern-matching/match.md +msgid "'w'" +msgstr "'w'" + +#: src/pattern-matching/match.md +msgid "'d'" +msgstr "'d'" + +#: src/pattern-matching/match.md +msgid "\"Moving around\"" +msgstr "" + +#: src/pattern-matching/match.md src/error-handling/exercise.md +#: src/error-handling/solution.md +msgid "'0'" +msgstr "'0'" + +#: src/pattern-matching/match.md src/error-handling/exercise.md +#: src/error-handling/solution.md +msgid "'9'" +msgstr "'9'" + +#: src/pattern-matching/match.md +msgid "\"Number input\"" +msgstr "" + +#: src/pattern-matching/match.md +msgid "\"Lowercase: {key}\"" +msgstr "" + +#: src/pattern-matching/match.md +msgid "\"Something else\"" +msgstr "" + +#: src/pattern-matching/match.md +msgid "" +"The `_` pattern is a wildcard pattern which matches any value. The " +"expressions _must_ be exhaustive, meaning that it covers every possibility, " +"so `_` is often used as the final catch-all case." +msgstr "" + +#: src/pattern-matching/match.md +#, fuzzy +msgid "" +"Match can be used as an expression. Just like `if`, each match arm must have " +"the same type. The type is the last expression of the block, if any. In the " +"example above, the type is `()`." +msgstr "" +"和 `if let` 一樣,每個比對臂都必須具有相同型別。型別是區塊的最後一個運算式 " +"(如有)。在上述範例中,型別為 `()`。" + +#: src/pattern-matching/match.md +msgid "" +"A variable in the pattern (`key` in this example) will create a binding that " +"can be used within the match arm." +msgstr "" + +#: src/pattern-matching/match.md +msgid "A match guard causes the arm to match only if the condition is true." +msgstr "" + +#: src/pattern-matching/match.md msgid "" "You might point out how some specific characters are being used when in a " "pattern" msgstr "建議您特別指出某些特定字元在模式中的使用方式" -#: src/pattern-matching.md:27 +#: src/pattern-matching/match.md msgid "`|` as an `or`" msgstr "`|` 可做為 `or`" -#: src/pattern-matching.md:28 +#: src/pattern-matching/match.md msgid "`..` can expand as much as it needs to be" msgstr "`..` 可以視需要展開" -#: src/pattern-matching.md:29 +#: src/pattern-matching/match.md msgid "`1..=5` represents an inclusive range" msgstr "`1..=5` 代表含頭尾的範圍" -#: src/pattern-matching.md:30 +#: src/pattern-matching/match.md msgid "`_` is a wild card" msgstr "`_` 是萬用字元" -#: src/pattern-matching.md:31 -msgid "" -"It can be useful to show how binding works, by for instance replacing a " -"wildcard character with a variable, or removing the quotes around `q`." -msgstr "" -"示範綁定的運作方式可能會很有幫助,例如您可以將萬用字元取代為變數,或是移除 " -"`q` 前後的引號。" - -#: src/pattern-matching.md:32 -msgid "You can demonstrate matching on a reference." -msgstr "您可以在參照項目上示範如何配對。" - -#: src/pattern-matching.md:33 -msgid "" -"This might be a good time to bring up the concept of irrefutable patterns, " -"as the term can show up in error messages." -msgstr "" -"這時候可能很適合提到「不可反駁的模式」這個概念,因為這個詞可能會出現在錯誤消" -"息中。" - -#: src/pattern-matching/destructuring-enums.md:3 -msgid "" -"Patterns can also be used to bind variables to parts of your values. This is " -"how you inspect the structure of your types. Let us start with a simple " -"`enum` type:" -msgstr "" -"模式也可用來將變數綁定至值的某些部分。您可以透過這個方式檢查型別的結構。首先" -"從簡單的 `enum` 型別開始吧:" - -#: src/pattern-matching/destructuring-enums.md:6 -msgid "" -"```rust,editable\n" -"enum Result {\n" -" Ok(i32),\n" -" Err(String),\n" -"}\n" -"\n" -"fn divide_in_two(n: i32) -> Result {\n" -" if n % 2 == 0 {\n" -" Result::Ok(n / 2)\n" -" } else {\n" -" Result::Err(format!(\"cannot divide {n} into two equal parts\"))\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let n = 100;\n" -" match divide_in_two(n) {\n" -" Result::Ok(half) => println!(\"{n} divided in two is {half}\"),\n" -" Result::Err(msg) => println!(\"sorry, an error happened: {msg}\"),\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/pattern-matching/destructuring-enums.md:29 -msgid "" -"Here we have used the arms to _destructure_ the `Result` value. In the first " -"arm, `half` is bound to the value inside the `Ok` variant. In the second " -"arm, `msg` is bound to the error message." -msgstr "" -"這裡我們利用分支來「解構」`Result` 值。在第一個分支中,`half` 會與 `Ok` 變體" -"中的值綁定。在第二個分支中,`msg` 會綁定至錯誤訊息。" - -#: src/pattern-matching/destructuring-enums.md:36 -msgid "" -"The `if`/`else` expression is returning an enum that is later unpacked with " -"a `match`." -msgstr "`if`/`else` 運算式會傳回列舉,之後列舉會透過 `match` 解除封裝。" - -#: src/pattern-matching/destructuring-enums.md:37 -msgid "" -"You can try adding a third variant to the enum definition and displaying the " -"errors when running the code. Point out the places where your code is now " -"inexhaustive and how the compiler tries to give you hints." -msgstr "" -"您可以嘗試在列舉定義中加入第三個變體,並在執行程式碼時顯示錯誤。請向學員指出" -"程式碼現在有哪些地方還不詳盡,並說明編譯器會如何嘗試給予提示。" - -#: src/pattern-matching/destructuring-structs.md:3 -msgid "You can also destructure `structs`:" -msgstr "您也可以解構 `struct`:" - -#: src/pattern-matching/destructuring-structs.md:5 -msgid "" -"```rust,editable\n" -"struct Foo {\n" -" x: (u32, u32),\n" -" y: u32,\n" -"}\n" -"\n" -"#[rustfmt::skip]\n" -"fn main() {\n" -" let foo = Foo { x: (1, 2), y: 3 };\n" -" match foo {\n" -" Foo { x: (1, b), y } => println!(\"x.0 = 1, b = {b}, y = {y}\"),\n" -" Foo { y: 2, x: i } => println!(\"y = 2, x = {i:?}\"),\n" -" Foo { y, .. } => println!(\"y = {y}, other fields were " -"ignored\"),\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/pattern-matching/destructuring-structs.md:23 -msgid "Change the literal values in `foo` to match with the other patterns." -msgstr "請變更 `foo` 中的常值,與其他模式配對。" - -#: src/pattern-matching/destructuring-structs.md:24 -msgid "Add a new field to `Foo` and make changes to the pattern as needed." -msgstr "在 `Foo` 中新增一個欄位,並視需要變更模式。" - -#: src/pattern-matching/destructuring-structs.md:25 -msgid "" -"The distinction between a capture and a constant expression can be hard to " -"spot. Try changing the `2` in the second arm to a variable, and see that it " -"subtly doesn't work. Change it to a `const` and see it working again." -msgstr "" -"捕獲和常數運算式之間的區別可能不容易發現。請嘗試將第二個分支的 `2` 變更為變" -"數,您會發現它幾乎無法運作。現在將其變更為 `const`,您會看到它再次運作。" - -#: src/pattern-matching/destructuring-arrays.md:3 -msgid "" -"You can destructure arrays, tuples, and slices by matching on their elements:" -msgstr "您可以在陣列、元組和切片的元素上配對,藉此解構陣列、元組和切片:" - -#: src/pattern-matching/destructuring-arrays.md:5 -msgid "" -"```rust,editable\n" -"#[rustfmt::skip]\n" -"fn main() {\n" -" let triple = [0, -2, 3];\n" -" println!(\"Tell me about {triple:?}\");\n" -" match triple {\n" -" [0, y, z] => println!(\"First is 0, y = {y}, and z = {z}\"),\n" -" [1, ..] => println!(\"First is 1 and the rest were ignored\"),\n" -" _ => println!(\"All elements were ignored\"),\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/pattern-matching/destructuring-arrays.md:21 -msgid "" -"Destructuring of slices of unknown length also works with patterns of fixed " -"length." -msgstr "您可以解構未知長度的切片,同樣的方法也適用於固定長度的模式。" - -#: src/pattern-matching/destructuring-arrays.md:24 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" inspect(&[0, -2, 3]);\n" -" inspect(&[0, -2, 3, 4]);\n" -"}\n" -"\n" -"#[rustfmt::skip]\n" -"fn inspect(slice: &[i32]) {\n" -" println!(\"Tell me about {slice:?}\");\n" -" match slice {\n" -" &[0, y, z] => println!(\"First is 0, y = {y}, and z = {z}\"),\n" -" &[1, ..] => println!(\"First is 1 and the rest were ignored\"),\n" -" _ => println!(\"All elements were ignored\"),\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/pattern-matching/destructuring-arrays.md:41 -msgid "Create a new pattern using `_` to represent an element. " -msgstr "建立使用 `_` 來代表元素的新模式。" - -#: src/pattern-matching/destructuring-arrays.md:42 -msgid "Add more values to the array." -msgstr "在陣列中加入更多值。" - -#: src/pattern-matching/destructuring-arrays.md:43 -msgid "" -"Point out that how `..` will expand to account for different number of " -"elements." -msgstr "向學員指出為了因應不同元素數量的情況,`..` 會如何展開。" - -#: src/pattern-matching/destructuring-arrays.md:44 -msgid "Show matching against the tail with patterns `[.., b]` and `[a@..,b]`" -msgstr "向學員說明與模式 (`[.., b]` 和 `[a@..,b]`) 末端的配對情形。" - -#: src/pattern-matching/match-guards.md:3 -msgid "" -"When matching, you can add a _guard_ to a pattern. This is an arbitrary " -"Boolean expression which will be executed if the pattern matches:" -msgstr "" -"配對時,您可以為模式新增「守衛」。這是任意的布林運算式,會在模式配對成功時執" -"行:" - -#: src/pattern-matching/match-guards.md:6 -msgid "" -"```rust,editable\n" -"#[rustfmt::skip]\n" -"fn main() {\n" -" let pair = (2, -2);\n" -" println!(\"Tell me about {pair:?}\");\n" -" match pair {\n" -" (x, y) if x == y => println!(\"These are twins\"),\n" -" (x, y) if x + y == 0 => println!(\"Antimatter, kaboom!\"),\n" -" (x, _) if x % 2 == 1 => println!(\"The first one is odd\"),\n" -" _ => println!(\"No correlation...\"),\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/pattern-matching/match-guards.md:23 +#: src/pattern-matching/match.md msgid "" "Match guards as a separate syntax feature are important and necessary when " "we wish to concisely express more complex ideas than patterns alone would " @@ -7081,7 +5102,7 @@ msgstr "" "有些概念比模式本身所允許的更加複雜,如果我們希望簡要地表達這些想法,就必須把" "配對守衛視為獨立的語法功能。" -#: src/pattern-matching/match-guards.md:24 +#: src/pattern-matching/match.md msgid "" "They are not the same as separate `if` expression inside of the match arm. " "An `if` expression inside of the branch block (after `=>`) happens after the " @@ -7092,452 +5113,147 @@ msgstr "" "後) 會在選取配對分支後發生。即使該區塊內的 `if` 條件失敗,系統也不會考量原始 " "`match` 運算式的其他分支。" -#: src/pattern-matching/match-guards.md:26 -msgid "You can use the variables defined in the pattern in your if expression." -msgstr "您可以在 if 運算式中使用模式內定義的變數。" - -#: src/pattern-matching/match-guards.md:27 +#: src/pattern-matching/match.md msgid "" "The condition defined in the guard applies to every expression in a pattern " "with an `|`." msgstr "只要運算式隸屬於具備 `|` 的模式之中,就會套用守衛定義的條件。" -#: src/exercises/day-2/morning.md:1 -msgid "Day 2: Morning Exercises" -msgstr "第 2 天:上午練習" +#: src/pattern-matching/destructuring.md +msgid "Like tuples, structs and enums can also be destructured by matching:" +msgstr "就像元組,結構體和列舉也可透過配對來解構:" -#: src/exercises/day-2/morning.md:3 -msgid "We will look at implementing methods in two contexts:" -msgstr "我們會探討如何在以下兩種情況下實作方法:" +#: src/pattern-matching/destructuring.md +msgid "Structs" +msgstr "結構體" -#: src/exercises/day-2/morning.md:5 -msgid "Simple struct which tracks health statistics." +#: src/pattern-matching/destructuring.md +msgid "\"x.0 = 1, b = {b}, y = {y}\"" +msgstr "\"x.0 = 1, b = {b}, y = {y}\"" + +#: src/pattern-matching/destructuring.md +msgid "\"y = 2, x = {i:?}\"" +msgstr "\"y = 2, x = {i:?}\"" + +#: src/pattern-matching/destructuring.md +msgid "\"y = {y}, other fields were ignored\"" +msgstr "\"y = {y}, other fields were ignored\"" + +#: src/pattern-matching/destructuring.md +msgid "" +"Patterns can also be used to bind variables to parts of your values. This is " +"how you inspect the structure of your types. Let us start with a simple " +"`enum` type:" msgstr "" +"模式也可用來將變數綁定至值的某些部分。您可以透過這個方式檢查型別的結構。首先" +"從簡單的 `enum` 型別開始吧:" -#: src/exercises/day-2/morning.md:7 -msgid "Multiple structs and enums for a drawing library." +#: src/pattern-matching/destructuring.md +msgid "\"cannot divide {n} into two equal parts\"" +msgstr "\"cannot divide {n} into two equal parts\"" + +#: src/pattern-matching/destructuring.md +msgid "\"{n} divided in two is {half}\"" +msgstr "\"{n} divided in two is {half}\"" + +#: src/pattern-matching/destructuring.md +msgid "\"sorry, an error happened: {msg}\"" +msgstr "\"sorry, an error happened: {msg}\"" + +#: src/pattern-matching/destructuring.md +msgid "" +"Here we have used the arms to _destructure_ the `Result` value. In the first " +"arm, `half` is bound to the value inside the `Ok` variant. In the second " +"arm, `msg` is bound to the error message." msgstr "" +"這裡我們利用分支來「解構」`Result` 值。在第一個分支中,`half` 會與 `Ok` 變體" +"中的值綁定。在第二個分支中,`msg` 會綁定至錯誤訊息。" -#: src/exercises/day-2/health-statistics.md:3 -msgid "" -"You're working on implementing a health-monitoring system. As part of that, " -"you need to keep track of users' health statistics." -msgstr "您正在實作健康監控系統,因此須追蹤使用者的健康統計資料。" +#: src/pattern-matching/destructuring.md +msgid "Change the literal values in `foo` to match with the other patterns." +msgstr "請變更 `foo` 中的常值,與其他模式配對。" -#: src/exercises/day-2/health-statistics.md:6 +#: src/pattern-matching/destructuring.md +msgid "Add a new field to `Foo` and make changes to the pattern as needed." +msgstr "在 `Foo` 中新增一個欄位,並視需要變更模式。" + +#: src/pattern-matching/destructuring.md msgid "" -"You'll start with some stubbed functions in an `impl` block as well as a " -"`User` struct definition. Your goal is to implement the stubbed out methods " -"on the `User` `struct` defined in the `impl` block." +"The distinction between a capture and a constant expression can be hard to " +"spot. Try changing the `2` in the second arm to a variable, and see that it " +"subtly doesn't work. Change it to a `const` and see it working again." msgstr "" -"您將從 `impl` 區塊中的部分虛設函式,以及 `User` 結構體定義著手,目標是在 " -"`impl` 區塊中定義的 `User` `struct` 上導入虛設常式方法。" +"捕獲和常數運算式之間的區別可能不容易發現。請嘗試將第二個分支的 `2` 變更為變" +"數,您會發現它幾乎無法運作。現在將其變更為 `const`,您會看到它再次運作。" -#: src/exercises/day-2/health-statistics.md:10 +#: src/pattern-matching/destructuring.md msgid "" -"Copy the code below to and fill in the missing " -"methods:" -msgstr "請將以下程式碼複製到 ,並填入缺少的方法:" +"The `if`/`else` expression is returning an enum that is later unpacked with " +"a `match`." +msgstr "`if`/`else` 運算式會傳回列舉,之後列舉會透過 `match` 解除封裝。" -#: src/exercises/day-2/health-statistics.md:13 +#: src/pattern-matching/destructuring.md msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"struct User {\n" -" name: String,\n" -" age: u32,\n" -" weight: f32,\n" -"}\n" -"\n" -"impl User {\n" -" pub fn new(name: String, age: u32, weight: f32) -> Self {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn name(&self) -> &str {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn age(&self) -> u32 {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn weight(&self) -> f32 {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn set_age(&mut self, new_age: u32) {\n" -" unimplemented!()\n" -" }\n" -"\n" -" pub fn set_weight(&mut self, new_weight: f32) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" -" println!(\"I'm {} and my age is {}\", bob.name(), bob.age());\n" -"}\n" -"\n" -"#[test]\n" -"fn test_weight() {\n" -" let bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" -" assert_eq!(bob.weight(), 155.2);\n" -"}\n" -"\n" -"#[test]\n" -"fn test_set_age() {\n" -" let mut bob = User::new(String::from(\"Bob\"), 32, 155.2);\n" -" assert_eq!(bob.age(), 32);\n" -" bob.set_age(33);\n" -" assert_eq!(bob.age(), 33);\n" -"}\n" -"```" +"You can try adding a third variant to the enum definition and displaying the " +"errors when running the code. Point out the places where your code is now " +"inexhaustive and how the compiler tries to give you hints." msgstr "" +"您可以嘗試在列舉定義中加入第三個變體,並在執行程式碼時顯示錯誤。請向學員指出" +"程式碼現在有哪些地方還不詳盡,並說明編譯器會如何嘗試給予提示。" -#: src/exercises/day-3/points-polygons.md:1 -msgid "Polygon Struct" -msgstr "多邊形結構體" - -#: src/exercises/day-3/points-polygons.md:3 +#: src/pattern-matching/destructuring.md +#, fuzzy msgid "" -"We will create a `Polygon` struct which contain some points. Copy the code " -"below to and fill in the missing methods to " -"make the tests pass:" +"The values in the enum variants can only be accessed after being pattern " +"matched." msgstr "" -"我們會建立一個包含某幾個點的 `Polygon` 結構體。請將下方程式碼複製到 ,並填入缺少的方法,設法通過測試:" +"只有在與模式配對相符後,才能存取列舉變數中的值。此模式會將參照繫結至 `=>` 後" +"方「配對分支」中的欄位。" -#: src/exercises/day-2/points-polygons.md:7 +#: src/pattern-matching/destructuring.md +#, fuzzy msgid "" -"```rust\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"pub struct Point {\n" -" // add fields\n" -"}\n" -"\n" -"impl Point {\n" -" // add methods\n" -"}\n" -"\n" -"pub struct Polygon {\n" -" // add fields\n" -"}\n" -"\n" -"impl Polygon {\n" -" // add methods\n" -"}\n" -"\n" -"pub struct Circle {\n" -" // add fields\n" -"}\n" -"\n" -"impl Circle {\n" -" // add methods\n" -"}\n" -"\n" -"pub enum Shape {\n" -" Polygon(Polygon),\n" -" Circle(Circle),\n" -"}\n" -"\n" -"#[cfg(test)]\n" -"mod tests {\n" -" use super::*;\n" -"\n" -" fn round_two_digits(x: f64) -> f64 {\n" -" (x * 100.0).round() / 100.0\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_magnitude() {\n" -" let p1 = Point::new(12, 13);\n" -" assert_eq!(round_two_digits(p1.magnitude()), 17.69);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_dist() {\n" -" let p1 = Point::new(10, 10);\n" -" let p2 = Point::new(14, 13);\n" -" assert_eq!(round_two_digits(p1.dist(p2)), 5.00);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_add() {\n" -" let p1 = Point::new(16, 16);\n" -" let p2 = p1 + Point::new(-4, 3);\n" -" assert_eq!(p2, Point::new(12, 19));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_left_most_point() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -" assert_eq!(poly.left_most_point(), Some(p1));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_iter() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -"\n" -" let points = poly.iter().cloned().collect::>();\n" -" assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_shape_perimeters() {\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(Point::new(12, 13));\n" -" poly.add_point(Point::new(17, 11));\n" -" poly.add_point(Point::new(16, 16));\n" -" let shapes = vec![\n" -" Shape::from(poly),\n" -" Shape::from(Circle::new(Point::new(10, 20), 5)),\n" -" ];\n" -" let perimeters = shapes\n" -" .iter()\n" -" .map(Shape::perimeter)\n" -" .map(round_two_digits)\n" -" .collect::>();\n" -" assert_eq!(perimeters, vec![15.48, 31.42]);\n" -" }\n" -"}\n" -"\n" -"#[allow(dead_code)]\n" -"fn main() {}\n" -"```" +"Demonstrate what happens when the search is inexhaustive. Note the advantage " +"the Rust compiler provides by confirming when all cases are handled." msgstr "" +"請示範非窮舉搜尋的情況。請確認系統處理所有案例的時間,指出 Rust 編譯器提供的" +"優勢。" -#: src/exercises/day-3/points-polygons.md:117 +#: src/pattern-matching/destructuring.md msgid "" -"Since the method signatures are missing from the problem statements, the key " -"part of the exercise is to specify those correctly. You don't have to modify " -"the tests." +"Save the result of `divide_in_two` in the `result` variable and `match` it " +"in a loop. That won't compile because `msg` is consumed when matched. To fix " +"it, match `&result` instead of `result`. That will make `msg` a reference so " +"it won't be consumed. This [\"match ergonomics\"](https://rust-lang.github." +"io/rfcs/2005-match-ergonomics.html) appeared in Rust 2018. If you want to " +"support older Rust, replace `msg` with `ref msg` in the pattern." msgstr "" -"由於問題陳述式缺少方法簽章,因此練習的關鍵部分就是正確指定這些簽章。您不需要" -"修改測試。" +"將 `divide_in_two` 的結果儲存在 `result` 變數中,並在迴圈中 `match` 結果。由" +"於配對符合時會耗用 `msg`,因此這麼做並不會執行編譯。如要修正此問題,請配對 " +"`&result`,而非 `result`。這會讓 `msg` 成為參照,因此就不會遭到耗用。這個" +"[「人因工程學的配對」](https://rust-lang.github.io/rfcs/2005-match-" +"ergonomics.html)功能已於 Rust 2018 推出。如要支援舊版 Rust,請在模式中將 " +"`msg` 替換成 `ref msg`。" -#: src/exercises/day-3/points-polygons.md:120 -msgid "Other interesting parts of the exercise:" -msgstr "練習中的其他有趣部分如下:" - -#: src/exercises/day-3/points-polygons.md:122 +#: src/pattern-matching/let-control-flow.md msgid "" -"Derive a `Copy` trait for some structs, as in tests the methods sometimes " -"don't borrow their arguments." -msgstr "針對部分結構體衍生 `Copy` 特徵,因為在測試中,方法有時不會借用其引數。" +"Rust has a few control flow constructs which differ from other languages. " +"They are used for pattern matching:" +msgstr "Rust 的某些控制流程結構與其他程式語言不同。這些結構會用於模式配對:" -#: src/exercises/day-3/points-polygons.md:123 -msgid "" -"Discover that `Add` trait must be implemented for two objects to be addable " -"via \"+\". Note that we do not discuss generics until Day 3." -msgstr "" -"發現必須實作 `Add` 特徵才能透過「+」新增兩個物件。請注意,我們在第 3 天以前不" -"會討論泛型。" - -#: src/control-flow.md:3 -msgid "" -"As we have seen, `if` is an expression in Rust. It is used to conditionally " -"evaluate one of two blocks, but the blocks can have a value which then " -"becomes the value of the `if` expression. Other control flow expressions " -"work similarly in Rust." -msgstr "" -"如同我們所見,`if` 是 Rust 中的一種表達式。它可以用來根據條件執行兩個區塊之中" -"的一個,而區塊的執行結果可以進一步轉變成 `if` 表達式的賦值。其他控制流程表達" -"式在 Rust 中也有類似的用法。" - -#: src/control-flow/blocks.md:3 -msgid "" -"A block in Rust has a value and a type: the value is the last expression of " -"the block:" -msgstr "" -"Rust 中的區塊 (Block) 包含一個數值以及一個型別:數值即為該區塊中的最後一行表" -"達式:" - -#: src/control-flow/blocks.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let x = {\n" -" let y = 10;\n" -" println!(\"y: {y}\");\n" -" let z = {\n" -" let w = {\n" -" 3 + 4\n" -" };\n" -" println!(\"w: {w}\");\n" -" y * w\n" -" };\n" -" println!(\"z: {z}\");\n" -" z - y\n" -" };\n" -" println!(\"x: {x}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let x = {\n" -" let y = 10;\n" -" println!(\"y: {y}\");\n" -" let z = {\n" -" let w = {\n" -" 3 + 4\n" -" };\n" -" println!(\"w: {w}\");\n" -" y * w\n" -" };\n" -" println!(\"z: {z}\");\n" -" z - y\n" -" };\n" -" println!(\"x: {x}\");\n" -"}\n" -"```" - -#: src/control-flow/blocks.md:25 -msgid "" -"The same rule is used for functions: the value of the function body is the " -"return value:" -msgstr "同樣的規則也適用於函式:函式的數值即為函式本體的回傳值:" - -#: src/control-flow/blocks.md:28 -msgid "" -"```rust,editable\n" -"fn double(x: i32) -> i32 {\n" -" x + x\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"doubled: {}\", double(7));\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn double(x: i32) -> i32 {\n" -" x + x\n" -"}\n" -"\n" -"fn main() {\n" -" println!(\"doubled: {}\", double(7));\n" -"}\n" -"```" - -#: src/control-flow/blocks.md:38 -msgid "" -"However if the last expression ends with `;`, then the resulting value and " -"type is `()`." -msgstr "然而,如果最後一行表達式的結尾為 `;`,則最後的數值及型別皆為 `()`。" - -#: src/control-flow/blocks.md:43 -msgid "" -"The point of this slide is to show that blocks have a type and value in " -"Rust. " -msgstr "這張投影片所表達的重點在於 Rust 中的區塊具有一個數值以及一個型別。" - -#: src/control-flow/blocks.md:44 -msgid "" -"You can show how the value of the block changes by changing the last line in " -"the block. For instance, adding/removing a semicolon or using a `return`." -msgstr "" -"你可以藉由改變區塊中的最後一行來觀察區塊數值的變化。舉例來說,新增或刪除一個" -"分號,或者使用 `return`。" - -#: src/control-flow/if-expressions.md:1 -msgid "`if` expressions" -msgstr "`if` 表達式" - -#: src/control-flow/if-expressions.md:3 -msgid "" -"You use [`if` expressions](https://doc.rust-lang.org/reference/expressions/" -"if-expr.html#if-expressions) exactly like `if` statements in other languages:" -msgstr "" -"你可以像在其他語言中使用 `if` 陳述式那樣地使用 [`if` 表達式](https://doc." -"rust-lang.org/reference/expressions/if-expr.html#if-expressions):" - -#: src/control-flow/if-expressions.md:7 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" if x % 2 == 0 {\n" -" x = x / 2;\n" -" } else {\n" -" x = 3 * x + 1;\n" -" }\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" if x % 2 == 0 {\n" -" x = x / 2;\n" -" } else {\n" -" x = 3 * x + 1;\n" -" }\n" -"}\n" -"```" - -#: src/control-flow/if-expressions.md:18 -msgid "" -"In addition, you can use `if` as an expression. The last expression of each " -"block becomes the value of the `if` expression:" -msgstr "" -"此外,你也可以將 `if` 當作表達式使用。每個區塊中的最後一行式子將成為 `if` 表" -"達式的賦值:" - -#: src/control-flow/if-expressions.md:22 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -"}\n" -"```" - -#: src/control-flow/if-expressions.md:35 -msgid "" -"Because `if` is an expression and must have a particular type, both of its " -"branch blocks must have the same type. Consider showing what happens if you " -"add `;` after `x / 2` in the second example." -msgstr "" -"因為 `if` 被當作表達式使用,它必須擁有一個特定的型別,因此兩個分支區塊必須擁" -"有同樣的型別。試著在第二個範例中的 `x / 2` 之後加上 `;`,並觀察其結果。" - -#: src/control-flow/if-let-expressions.md:1 +#: src/pattern-matching/let-control-flow.md msgid "`if let` expressions" msgstr "`if let` 運算式" -#: src/control-flow/if-let-expressions.md:3 +#: src/pattern-matching/let-control-flow.md +msgid "`while let` expressions" +msgstr "`while let` 運算式" + +#: src/pattern-matching/let-control-flow.md +msgid "`match` expressions" +msgstr "`match` 運算式" + +#: src/pattern-matching/let-control-flow.md msgid "" "The [`if let` expression](https://doc.rust-lang.org/reference/expressions/if-" "expr.html#if-let-expressions) lets you execute different code depending on " @@ -7546,144 +5262,48 @@ msgstr "" "[`if let` 運算式](https://doc.rust-lang.org/reference/expressions/if-expr." "html#if-let-expressions)可讓您根據值是否符合模式,執行不同的程式碼:" -#: src/control-flow/if-let-expressions.md:7 +#: src/pattern-matching/let-control-flow.md +msgid "\"slept for {:?}\"" +msgstr "\"slept for {:?}\"" + +#: src/pattern-matching/let-control-flow.md +msgid "`let else` expressions" +msgstr "`let else` 運算式" + +#: src/pattern-matching/let-control-flow.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let arg = std::env::args().next();\n" -" if let Some(value) = arg {\n" -" println!(\"Program name: {value}\");\n" -" } else {\n" -" println!(\"Missing name?\");\n" -" }\n" -"}\n" -"```" +"For the common case of matching a pattern and returning from the function, " +"use [`let else`](https://doc.rust-lang.org/rust-by-example/flow_control/" +"let_else.html). The \"else\" case must diverge (`return`, `break`, or panic " +"- anything but falling off the end of the block)." msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let arg = std::env::args().next();\n" -" if let Some(value) = arg {\n" -" println!(\"Program name: {value}\");\n" -" } else {\n" -" println!(\"Missing name?\");\n" -" }\n" -"}\n" -"```" +"如果是要配對模式並從函式傳回的常見情況,請使用 [`let else`](https://doc.rust-" +"lang.org/rust-by-example/flow_control/let_else.html)。如果是「其他」情況,則" +"必須發散 (`return`、`break` 或恐慌,也就是落在區塊結尾之外的任何情況)。" -#: src/control-flow/if-let-expressions.md:18 -#: src/control-flow/while-let-expressions.md:21 -#: src/control-flow/match-expressions.md:23 -msgid "" -"See [pattern matching](../pattern-matching.md) for more details on patterns " -"in Rust." -msgstr "" -"如要進一步瞭解 Rust 中的模式,請參閱「[模式比對](../pattern-matching.md)」。" +#: src/pattern-matching/let-control-flow.md +msgid "\"got None\"" +msgstr "\"got None\"" -#: src/control-flow/if-let-expressions.md:23 -msgid "" -"`if let` can be more concise than `match`, e.g., when only one case is " -"interesting. In contrast, `match` requires all branches to be covered." -msgstr "" -"`if let` 可以比 `match` 更為精簡,例如只有一個有趣案例時。相對地,`match` 必" -"須涵蓋所有分支。" +#: src/pattern-matching/let-control-flow.md +msgid "\"got empty string\"" +msgstr "\"got empty string\"" -#: src/control-flow/if-let-expressions.md:24 -msgid "A common usage is handling `Some` values when working with `Option`." -msgstr "常見用途是在使用 `Option` 時處理 `Some` 值。" +#: src/pattern-matching/let-control-flow.md +msgid "\"not a hex digit\"" +msgstr "\"not a hex digit\"" -#: src/control-flow/if-let-expressions.md:25 -msgid "" -"Unlike `match`, `if let` does not support guard clauses for pattern matching." -msgstr "與 `match` 不同,`if let` 不會為模式比對支援成立條件子句。" +#: src/pattern-matching/let-control-flow.md src/pattern-matching/solution.md +msgid "\"result: {:?}\"" +msgstr "\"result: {:?}\"" -#: src/control-flow/if-let-expressions.md:26 -msgid "" -"Since 1.65, a similar [let-else](https://doc.rust-lang.org/rust-by-example/" -"flow_control/let_else.html) construct allows to do a destructuring " -"assignment, or if it fails, have a non-returning block branch (panic/return/" -"break/continue):" -msgstr "" -"自 1.65 版起,類似的 [let-else](https://doc.rust-lang.org/rust-by-example/" -"flow_control/let_else.html) 結構可以解構指派項目,或在失敗時具有不會傳回的區" -"塊分支 (panic/return/break/continue):" +#: src/pattern-matching/let-control-flow.md src/generics/trait-bounds.md +#: src/smart-pointers/solution.md src/testing/solution.md +#: src/android/testing.md src/android/testing/googletest.md +msgid "\"foo\"" +msgstr "\"foo\"" -#: src/control-flow/if-let-expressions.md:28 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"{:?}\", second_word_to_upper(\"foo bar\"));\n" -"}\n" -" \n" -"fn second_word_to_upper(s: &str) -> Option {\n" -" let mut it = s.split(' ');\n" -" let (Some(_), Some(item)) = (it.next(), it.next()) else {\n" -" return None;\n" -" };\n" -" Some(item.to_uppercase())\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" println!(\"{:?}\", second_word_to_upper(\"foo bar\"));\n" -"}\n" -" \n" -"fn second_word_to_upper(s: &str) -> Option {\n" -" let mut it = s.split(' ');\n" -" let (Some(_), Some(item)) = (it.next(), it.next()) else {\n" -" return None;\n" -" };\n" -" Some(item.to_uppercase())\n" -"}\n" -"```" - -#: src/control-flow/while-expressions.md:1 -msgid "`while` loops" -msgstr "`while` 迴圈" - -#: src/control-flow/while-expressions.md:3 -msgid "" -"The [`while` keyword](https://doc.rust-lang.org/reference/expressions/loop-" -"expr.html#predicate-loops) works very similar to other languages:" -msgstr "" -"[`while` 關鍵字](https://doc.rust-lang.org/reference/expressions/loop-expr." -"html#predicate-loops)的運作方式與其他語言非常相似:" - -#: src/control-flow/while-expressions.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" while x != 1 {\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -" }\n" -" println!(\"Final x: {x}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" while x != 1 {\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -" }\n" -" println!(\"Final x: {x}\");\n" -"}\n" -"```" - -#: src/control-flow/while-let-expressions.md:1 -msgid "`while let` loops" -msgstr "`while let` 迴圈" - -#: src/control-flow/while-let-expressions.md:3 +#: src/pattern-matching/let-control-flow.md msgid "" "Like with `if let`, there is a [`while let`](https://doc.rust-lang.org/" "reference/expressions/loop-expr.html#predicate-pattern-loops) variant which " @@ -7693,1675 +5313,588 @@ msgstr "" "reference/expressions/loop-expr.html#predicate-pattern-loops) 變數可針對模式" "重複測試值:" -#: src/control-flow/while-let-expressions.md:6 +#: src/pattern-matching/let-control-flow.md +#, fuzzy msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let mut iter = v.into_iter();\n" -"\n" -" while let Some(x) = iter.next() {\n" -" println!(\"x: {x}\");\n" -" }\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let mut iter = v.into_iter();\n" -"\n" -" while let Some(x) = iter.next() {\n" -" println!(\"x: {x}\");\n" -" }\n" -"}\n" -"```" - -#: src/control-flow/while-let-expressions.md:17 -msgid "" -"Here the iterator returned by `v.iter()` will return a `Option` on " -"every call to `next()`. It returns `Some(x)` until it is done, after which " -"it will return `None`. The `while let` lets us keep iterating through all " -"items." +"Here [`String::pop`](https://doc.rust-lang.org/stable/std/string/struct." +"String.html#method.pop) returns `Some(c)` until the string is empty, after " +"which it will return `None`. The `while let` lets us keep iterating through " +"all items." msgstr "" "`v.iter()` 傳回的疊代器會在每次呼叫 `next()` 時傳回 `Option`。疊代器會在" "完成後才傳回 `Some(x)`,之後則會傳回 `None`。`while let` 可讓我們持續疊代所有" "項目。" -#: src/control-flow/while-let-expressions.md:26 +#: src/pattern-matching/let-control-flow.md +msgid "if-let" +msgstr "if-let" + +#: src/pattern-matching/let-control-flow.md +#, fuzzy +msgid "" +"Unlike `match`, `if let` does not have to cover all branches. This can make " +"it more concise than `match`." +msgstr "與 `match` 不同,`if let` 不會為模式比對支援成立條件子句。" + +#: src/pattern-matching/let-control-flow.md +msgid "A common usage is handling `Some` values when working with `Option`." +msgstr "常見用途是在使用 `Option` 時處理 `Some` 值。" + +#: src/pattern-matching/let-control-flow.md +msgid "" +"Unlike `match`, `if let` does not support guard clauses for pattern matching." +msgstr "與 `match` 不同,`if let` 不會為模式比對支援成立條件子句。" + +#: src/pattern-matching/let-control-flow.md +msgid "let-else" +msgstr "let-else" + +#: src/pattern-matching/let-control-flow.md +msgid "" +"`if-let`s can pile up, as shown. The `let-else` construct supports " +"flattening this nested code. Rewrite the awkward version for students, so " +"they can see the transformation." +msgstr "" +"如上所示,`if-let` 可能會越加越多。`let-else` 結構支援壓平合併這個巢狀程式" +"碼。請為學生重新編寫這個冗長的版本,讓他們見識改寫的效果。" + +#: src/pattern-matching/let-control-flow.md +msgid "The rewritten version is:" +msgstr "重新編寫的版本如下:" + +#: src/pattern-matching/let-control-flow.md +msgid "while-let" +msgstr "while-let" + +#: src/pattern-matching/let-control-flow.md msgid "" "Point out that the `while let` loop will keep going as long as the value " "matches the pattern." msgstr "請指出只要值符合模式,`while let` 迴圈就會持續運作。" -#: src/control-flow/while-let-expressions.md:27 +#: src/pattern-matching/let-control-flow.md +#, fuzzy msgid "" "You could rewrite the `while let` loop as an infinite loop with an if " -"statement that breaks when there is no value to unwrap for `iter.next()`. " -"The `while let` provides syntactic sugar for the above scenario." +"statement that breaks when there is no value to unwrap for `name.pop()`. The " +"`while let` provides syntactic sugar for the above scenario." msgstr "" "您可以將 `while let` 迴圈重寫為無限迴圈,並加上會在無法為 `iter.next()` 取消" "包裝值的情況下結束的 if 陳述式。`while let` 可為上述情況提供語法糖。" -#: src/control-flow/for-expressions.md:1 -msgid "`for` loops" -msgstr "`for` 迴圈" +#: src/pattern-matching/exercise.md +msgid "Let's write a simple recursive evaluator for arithmetic expressions." +msgstr "我們現在要為算術運算式編寫簡單的遞迴評估器。" -#: src/control-flow/for-expressions.md:3 +#: src/pattern-matching/exercise.md msgid "" -"The [`for` loop](https://doc.rust-lang.org/std/keyword.for.html) is closely " -"related to the [`while let` loop](while-let-expression.md). It will " -"automatically call `into_iter()` on the expression and then iterate over it:" +"The `Box` type here is a smart pointer, and will be covered in detail later " +"in the course. An expression can be \"boxed\" with `Box::new` as seen in the " +"tests. To evaluate a boxed expression, use the deref operator (`*`) to " +"\"unbox\" it: `eval(*boxed_expr)`." msgstr "" -"[`for` 迴圈](https://doc.rust-lang.org/std/keyword.for.html)與 [`while let` " -"迴圈](while-let-expression.md)密切相關,會自動在運算式上呼叫 `into_iter()`," -"然後對其進行疊代:" +"這裡的 `Box` 型別是一種智慧指標,我們會在本課程的後續部分詳細說明。如測試中所" +"示,運算式可被 `Box::new`「裝箱」。如要求裝箱運算式的值,請使用 deref 運算子 " +"(`*`) 來「開箱」:`eval(*boxed_expr)`。" -#: src/control-flow/for-expressions.md:7 +#: src/pattern-matching/exercise.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -"\n" -" for x in v {\n" -" println!(\"x: {x}\");\n" -" }\n" -" \n" -" for i in (0..10).step_by(2) {\n" -" println!(\"i: {i}\");\n" -" }\n" -"}\n" -"```" +"Some expressions cannot be evaluated and will return an error. The standard " +"[`Result`](https://doc.rust-lang.org/std/result/enum.Result." +"html) type is an enum that represents either a successful value " +"(`Ok(Value)`) or an error (`Err(String)`). We will cover this type in detail " +"later." msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -"\n" -" for x in v {\n" -" println!(\"x: {x}\");\n" -" }\n" -" \n" -" for i in (0..10).step_by(2) {\n" -" println!(\"i: {i}\");\n" -" }\n" -"}\n" -"```" +"部分運算式無法求值,且會傳回錯誤。標準 [`Result`](https://doc." +"rust-lang.org/std/result/enum.Result.html) 型別是一種列舉,用於表示成功值 " +"(`Ok(Value) )`) 或錯誤 (`Err(String)`)。我們稍後會詳細說明這種型別。" -#: src/control-flow/for-expressions.md:21 -msgid "You can use `break` and `continue` here as usual." -msgstr "您可以照常使用 `break` 和 `continue`。" - -#: src/control-flow/for-expressions.md:25 -msgid "Index iteration is not a special syntax in Rust for just that case." -msgstr "在 Rust 中,索引疊代不是只適用於該情況的特殊語法。" - -#: src/control-flow/for-expressions.md:26 -msgid "`(0..10)` is a range that implements an `Iterator` trait. " -msgstr "`(0..10)` 是實作 `Iterator` 特徵的範圍。" - -#: src/control-flow/for-expressions.md:27 +#: src/pattern-matching/exercise.md msgid "" -"`step_by` is a method that returns another `Iterator` that skips every other " -"element. " -msgstr "`step_by` 這個方法會傳回另一個略過其他所有元素的 `Iterator`。" - -#: src/control-flow/for-expressions.md:28 -msgid "" -"Modify the elements in the vector and explain the compiler errors. Change " -"vector `v` to be mutable and the for loop to `for x in v.iter_mut()`." +"Copy and paste the code into the Rust playground, and begin implementing " +"`eval`. The final product should pass the tests. It may be helpful to use " +"`todo!()` and get the tests to pass one-by-one. You can also skip a test " +"temporarily with `#[ignore]`:" msgstr "" -"請修改向量中的元素,並說明編譯器錯誤。將向量 `v` 變更為可變動項,並將 for 迴" -"圈變更為 `for x in v.iter_mut()`。" +"請複製程式碼並貼到 Rust Playground,然後開始實作 `eval`。最終成品應會通過測" +"試。使用 `todo!()` 讓測試逐一通過可能有所幫助,但您也可以使用 `#[ignore]` 暫" +"時略過測試:" -#: src/control-flow/loop-expressions.md:1 -msgid "`loop` expressions" -msgstr "`loop` 運算式" - -#: src/control-flow/loop-expressions.md:3 +#: src/pattern-matching/exercise.md msgid "" -"Finally, there is a [`loop` keyword](https://doc.rust-lang.org/reference/" -"expressions/loop-expr.html#infinite-loops) which creates an endless loop." +"If you finish early, try writing a test that results in division by zero or " +"integer overflow. How could you handle this with `Result` instead of a panic?" msgstr "" -"最後,有一個 [`loop` 關鍵字](https://doc.rust-lang.org/reference/expressions/" -"loop-expr.html#infinite-loops)會建立無限迴圈。" +"如果您提前完成操作,不妨試著編寫一個以零為除數或會整數溢位的測試。該如何利用 " +"`Result` (而非恐慌) 處理這種情況?" -#: src/control-flow/loop-expressions.md:6 -msgid "Here you must either `break` or `return` to stop the loop:" -msgstr "這時您必須執行 `break` 或 `return` 來停止迴圈:" +#: src/pattern-matching/exercise.md src/pattern-matching/solution.md +msgid "/// An operation to perform on two subexpressions.\n" +msgstr "/// An operation to perform on two subexpressions.\n" -#: src/control-flow/loop-expressions.md:8 +#: src/pattern-matching/exercise.md src/pattern-matching/solution.md +msgid "/// An expression, in tree form.\n" +msgstr "/// An expression, in tree form.\n" + +#: src/pattern-matching/exercise.md src/pattern-matching/solution.md +msgid "/// An operation on two subexpressions.\n" +msgstr "/// An operation on two subexpressions.\n" + +#: src/pattern-matching/exercise.md src/pattern-matching/solution.md +msgid "/// A literal value\n" +msgstr "/// A literal value\n" + +#: src/pattern-matching/exercise.md src/pattern-matching/solution.md +msgid "\"division by zero\"" +msgstr "\"division by zero\"" + +#: src/pattern-matching/solution.md +msgid "\"expr: {:?}\"" +msgstr "\"expr: {:?}\"" + +#: src/methods-and-traits.md +msgid "[Methods](./methods-and-traits/methods.md) (10 minutes)" +msgstr "[方法](./methods-and-traits/methods.md) (10 分鐘)" + +#: src/methods-and-traits.md +msgid "[Traits](./methods-and-traits/traits.md) (10 minutes)" +msgstr "[特徵](./methods-and-traits/traits.md) (10 分鐘)" + +#: src/methods-and-traits.md +msgid "[Deriving](./methods-and-traits/deriving.md) (3 minutes)" +msgstr "[衍生](./methods-and-traits/deriving.md) (3 分鐘)" + +#: src/methods-and-traits.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" loop {\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -" if x == 1 {\n" -" break;\n" -" }\n" -" }\n" -" println!(\"Final x: {x}\");\n" -"}\n" -"```" +"[Exercise: Generic Logger](./methods-and-traits/exercise.md) (20 minutes)" +msgstr "[練習:泛型 Logger](./methods-and-traits/exercise.md) (20 分鐘)" + +#: src/methods-and-traits/methods.md +msgid "" +"Rust allows you to associate functions with your new types. You do this with " +"an `impl` block:" msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let mut x = 10;\n" -" loop {\n" -" x = if x % 2 == 0 {\n" -" x / 2\n" -" } else {\n" -" 3 * x + 1\n" -" };\n" -" if x == 1 {\n" -" break;\n" -" }\n" -" }\n" -" println!(\"Final x: {x}\");\n" -"}\n" -"```" +"Rust 可讓您將函式與新型別建立關聯。您可以使用 `impl` 區塊來執行這項操作:" -#: src/control-flow/loop-expressions.md:27 -msgid "Break the `loop` with a value (e.g. `break 8`) and print it out." -msgstr "請使用 `break 8` 等值中斷 `loop`,然後顯示出來。" +#: src/methods-and-traits/methods.md +msgid "// No receiver, a static method\n" +msgstr "// No receiver, a static method\n" -#: src/control-flow/loop-expressions.md:28 -msgid "" -"Note that `loop` is the only looping construct which returns a non-trivial " -"value. This is because it's guaranteed to be entered at least once (unlike " -"`while` and `for` loops)." -msgstr "" -"請注意,`loop` 是唯一會傳回重要值的迴圈結構。這是因為系統保證至少會輸入一次此" -"迴圈結構,這一點不同於 `while` 和 `for` 迴圈。" +#: src/methods-and-traits/methods.md +msgid "// Exclusive borrowed read-write access to self\n" +msgstr "// Exclusive borrowed read-write access to self\n" -#: src/control-flow/match-expressions.md:1 -msgid "`match` expressions" -msgstr "`match` 運算式" +#: src/methods-and-traits/methods.md +msgid "// Shared and read-only borrowed access to self\n" +msgstr "// Shared and read-only borrowed access to self\n" -#: src/control-flow/match-expressions.md:3 -msgid "" -"The [`match` keyword](https://doc.rust-lang.org/reference/expressions/match-" -"expr.html) is used to match a value against one or more patterns. In that " -"sense, it works like a series of `if let` expressions:" -msgstr "" -"[`match` 關鍵字](https://doc.rust-lang.org/reference/expressions/match-expr." -"html)是用來將值與一或多個模式進行比對。因此,這個關鍵字的運作方式類似於一系列" -"的 `if let` 運算式:" +#: src/methods-and-traits/methods.md +msgid "\"Recorded {} laps for {}:\"" +msgstr "\"Recorded {} laps for {}:\"" -#: src/control-flow/match-expressions.md:7 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" match std::env::args().next().as_deref() {\n" -" Some(\"cat\") => println!(\"Will do cat things\"),\n" -" Some(\"ls\") => println!(\"Will ls some files\"),\n" -" Some(\"mv\") => println!(\"Let's move some files\"),\n" -" Some(\"rm\") => println!(\"Uh, dangerous!\"),\n" -" None => println!(\"Hmm, no program name?\"),\n" -" _ => println!(\"Unknown program name!\"),\n" -" }\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" match std::env::args().next().as_deref() {\n" -" Some(\"cat\") => println!(\"Will do cat things\"),\n" -" Some(\"ls\") => println!(\"Will ls some files\"),\n" -" Some(\"mv\") => println!(\"Let's move some files\"),\n" -" Some(\"rm\") => println!(\"Uh, dangerous!\"),\n" -" None => println!(\"Hmm, no program name?\"),\n" -" _ => println!(\"Unknown program name!\"),\n" -" }\n" -"}\n" -"```" +#: src/methods-and-traits/methods.md +msgid "\"Lap {idx}: {lap} sec\"" +msgstr "\"Lap {idx}: {lap} sec\"" -#: src/control-flow/match-expressions.md:20 -msgid "" -"Like `if let`, each match arm must have the same type. The type is the last " -"expression of the block, if any. In the example above, the type is `()`." -msgstr "" -"和 `if let` 一樣,每個比對臂都必須具有相同型別。型別是區塊的最後一個運算式 " -"(如有)。在上述範例中,型別為 `()`。" +#: src/methods-and-traits/methods.md +msgid "// Exclusive ownership of self\n" +msgstr "// Exclusive ownership of self\n" -#: src/control-flow/match-expressions.md:28 -msgid "Save the match expression to a variable and print it out." -msgstr "請將比對運算式儲存為變數,然後顯示出來。" +#: src/methods-and-traits/methods.md +msgid "\"Race {} is finished, total lap time: {}\"" +msgstr "\"Race {} is finished, total lap time: {}\"" -#: src/control-flow/match-expressions.md:29 -msgid "Remove `.as_deref()` and explain the error." -msgstr "請移除 `.as_deref()` 並說明錯誤。" +#: src/methods-and-traits/methods.md +msgid "\"Monaco Grand Prix\"" +msgstr "\"Monaco Grand Prix\"" -#: src/control-flow/match-expressions.md:30 -msgid "" -"`std::env::args().next()` returns an `Option`, but we cannot match " -"against `String`." -msgstr "" -"`std::env::args().next()` 會傳回 `Option`,但我們無法與`String` 進行" -"比對。" +#: src/methods-and-traits/methods.md +msgid "// race.add_lap(42);\n" +msgstr "// race.add_lap(42);\n" -#: src/control-flow/match-expressions.md:31 -msgid "" -"`as_deref()` transforms an `Option` to `Option<&T::Target>`. In our case, " -"this turns `Option` into `Option<&str>`." -msgstr "" -"`as_deref()` 會將 `Option` 轉換成 `Option<&T::Target>`。在我們的案例中,這" -"會將 `Option` 轉換成`Option<&str>`。" - -#: src/control-flow/match-expressions.md:32 -msgid "" -"We can now use pattern matching to match against the `&str` inside `Option`." -msgstr "我們現在可以使用模式比對,與 `Option` 內的 `&str` 進行比對。" - -#: src/control-flow/break-continue.md:1 -msgid "`break` and `continue`" -msgstr "`break` 和 `continue`" - -#: src/control-flow/break-continue.md:3 -msgid "" -"If you want to exit a loop early, use [`break`](https://doc.rust-lang.org/" -"reference/expressions/loop-expr.html#break-expressions)," -msgstr "" -"如果你想提早跳出迴圈,可以使用 [`break`]((https://doc.rust-lang.org/" -"reference/expressions/loop-expr.html#break-expressions))," - -#: src/control-flow/break-continue.md:4 -msgid "" -"If you want to immediately start the next iteration use [`continue`](https://" -"doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions)." -msgstr "" -"如果你想立即進入下一次迭代,可以使用 [`continue`](https://doc.rust-lang.org/" -"reference/expressions/loop-expr.html#continue-expressions)。" - -#: src/control-flow/break-continue.md:7 -msgid "" -"Both `continue` and `break` can optionally take a label argument which is " -"used to break out of nested loops:" -msgstr "" -"`continue` 以及 `break` 都可以選擇性地接收一個迴圈標籤,用來跳出巢狀迴圈中的" -"某一層:" - -#: src/control-flow/break-continue.md:10 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let mut iter = v.into_iter();\n" -" 'outer: while let Some(x) = iter.next() {\n" -" println!(\"x: {x}\");\n" -" let mut i = 0;\n" -" while i < x {\n" -" println!(\"x: {x}, i: {i}\");\n" -" i += 1;\n" -" if i == 3 {\n" -" break 'outer;\n" -" }\n" -" }\n" -" }\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let mut iter = v.into_iter();\n" -" 'outer: while let Some(x) = iter.next() {\n" -" println!(\"x: {x}\");\n" -" let mut i = 0;\n" -" while i < x {\n" -" println!(\"x: {x}, i: {i}\");\n" -" i += 1;\n" -" if i == 3 {\n" -" break 'outer;\n" -" }\n" -" }\n" -" }\n" -"}\n" -"```" - -#: src/control-flow/break-continue.md:28 -msgid "" -"In this case we break the outer loop after 3 iterations of the inner loop." -msgstr "在這個範例中,內層迴圈經過三次迭代後,我們使用 `break` 跳出外層迴圈。" - -#: src/std.md:3 -msgid "" -"Rust comes with a standard library which helps establish a set of common " -"types used by Rust library and programs. This way, two libraries can work " -"together smoothly because they both use the same `String` type." -msgstr "" -"Rust 提供標準函式庫,可用於建立供 Rust 函式庫和程式使用的常用型別集。如此一" -"來,兩個函式庫會使用相同的 `String` 型別,因此能夠順暢搭配運作。" - -#: src/std.md:7 -msgid "The common vocabulary types include:" -msgstr "常見的詞彙型別包括:" - -#: src/std.md:9 -msgid "" -"[`Option` and `Result`](std/option-result.md) types: used for optional " -"values and [error handling](error-handling.md)." -msgstr "" -"[`Option` 和 `Result`](std/option-result.md) 型別:用於選擇性的值和[錯誤處理]" -"(error-handling.md)。" - -#: src/std.md:12 -msgid "[`String`](std/string.md): the default string type used for owned data." -msgstr "[`String`](std/string.md):用於自有資料的預設字串型別。" - -#: src/std.md:14 -msgid "[`Vec`](std/vec.md): a standard extensible vector." -msgstr "[`Vec`](std/vec.md):標準的可延伸向量。" - -#: src/std.md:16 -msgid "" -"[`HashMap`](std/hashmap.md): a hash map type with a configurable hashing " -"algorithm." -msgstr "[`HashMap`](std/hashmap.md):採用可設定雜湊演算法的雜湊映射型別。" - -#: src/std.md:19 -msgid "[`Box`](std/box.md): an owned pointer for heap-allocated data." -msgstr "[`Box`](std/box.md):堆積配置資料的擁有所有權的指標。" - -#: src/std.md:21 -msgid "" -"[`Rc`](std/rc.md): a shared reference-counted pointer for heap-allocated " -"data." -msgstr "[`Rc`](std/rc.md):堆積配置資料的共用參考指標。" - -#: src/std.md:25 -msgid "" -"In fact, Rust contains several layers of the Standard Library: `core`, " -"`alloc` and `std`. " -msgstr "Rust 實際上含有多種層級的標準函式庫,分別是 `core`、`alloc` 和 `std`。" - -#: src/std.md:26 -msgid "" -"`core` includes the most basic types and functions that don't depend on " -"`libc`, allocator or even the presence of an operating system. " -msgstr "" -"`core` 包括最基本的型別與函式,這些型別與函式不依附於 `libc`、配置器或作業系" -"統。" - -#: src/std.md:28 -msgid "" -"`alloc` includes types which require a global heap allocator, such as `Vec`, " -"`Box` and `Arc`." -msgstr "`alloc` 包括需要全域堆積配置器的型別,例如 `Vec`、`Box` 和 `Arc`。" - -#: src/std.md:29 -msgid "" -"Embedded Rust applications often only use `core`, and sometimes `alloc`." -msgstr "嵌入式 Rust 應用程式通常只使用 `core`,偶爾會使用 `alloc`。" - -#: src/std/option-result.md:1 -msgid "`Option` and `Result`" -msgstr "`Option` 和 `Result`" - -#: src/std/option-result.md:3 -msgid "The types represent optional data:" -msgstr "這些型別代表選擇性的資料:" - -#: src/std/option-result.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let numbers = vec![10, 20, 30];\n" -" let first: Option<&i8> = numbers.first();\n" -" println!(\"first: {first:?}\");\n" -"\n" -" let idx: Result = numbers.binary_search(&10);\n" -" println!(\"idx: {idx:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/std/option-result.md:18 -msgid "`Option` and `Result` are widely used not just in the standard library." -msgstr "`Option` 和 `Result` 這兩種型別的使用範圍很廣,不侷限於標準函式庫。" - -#: src/std/option-result.md:19 -msgid "`Option<&T>` has zero space overhead compared to `&T`." -msgstr "相較於 `&T`,`Option<&T>` 的空間開銷為零。" - -#: src/std/option-result.md:20 -msgid "" -"`Result` is the standard type to implement error handling as we will see on " -"Day 3." -msgstr "`Result` 是實作錯誤處理的標準型別,我們將在第 3 天的課程中介紹。" - -#: src/std/option-result.md:21 -msgid "`binary_search` returns `Result`." -msgstr "`binary_search` 會回傳 `Result`。" - -#: src/std/option-result.md:22 -msgid "If found, `Result::Ok` holds the index where the element is found." -msgstr "如果找到該元素,`Result::Ok` 會保留該元素所在位置的索引。" - -#: src/std/option-result.md:23 -msgid "" -"Otherwise, `Result::Err` contains the index where such an element should be " -"inserted." -msgstr "如果沒有找到,`Result::Err` 會包含應插入這類元素的索引。" - -#: src/std/string.md:3 -msgid "" -"[`String`](https://doc.rust-lang.org/std/string/struct.String.html) is the " -"standard heap-allocated growable UTF-8 string buffer:" -msgstr "" -"[`String`](https://doc.rust-lang.org/std/string/struct.String.html) 是標準堆" -"積配置的可成長 UTF-8 字串緩衝區:" - -#: src/std/string.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut s1 = String::new();\n" -" s1.push_str(\"Hello\");\n" -" println!(\"s1: len = {}, capacity = {}\", s1.len(), s1.capacity());\n" -"\n" -" let mut s2 = String::with_capacity(s1.len() + 1);\n" -" s2.push_str(&s1);\n" -" s2.push('!');\n" -" println!(\"s2: len = {}, capacity = {}\", s2.len(), s2.capacity());\n" -"\n" -" let s3 = String::from(\"🇨🇭\");\n" -" println!(\"s3: len = {}, number of chars = {}\", s3.len(),\n" -" s3.chars().count());\n" -"}\n" -"```" -msgstr "" - -#: src/std/string.md:22 -msgid "" -"`String` implements [`Deref`](https://doc.rust-lang.org/std/" -"string/struct.String.html#deref-methods-str), which means that you can call " -"all `str` methods on a `String`." -msgstr "" -"`String` 會實作 [`Deref`](https://doc.rust-lang.org/std/string/" -"struct.String.html#deref-methods-str)。也就是說,您可以在 `String` 上呼叫所" -"有 `str` 方法。" - -#: src/std/string.md:30 -msgid "" -"`String::new` returns a new empty string, use `String::with_capacity` when " -"you know how much data you want to push to the string." -msgstr "" -"`String::new` 會傳回新的空白字串,如果您知道要向字串推送多少資料,請使用 " -"`String::with_capacity`。" - -#: src/std/string.md:31 -msgid "" -"`String::len` returns the size of the `String` in bytes (which can be " -"different from its length in characters)." -msgstr "" -"`String::len` 會傳回 `String` 的大小 (以位元組為單位,可能與以字元為單位的長" -"度不同)。" - -#: src/std/string.md:32 -msgid "" -"`String::chars` returns an iterator over the actual characters. Note that a " -"`char` can be different from what a human will consider a \"character\" due " -"to [grapheme clusters](https://docs.rs/unicode-segmentation/latest/" -"unicode_segmentation/struct.Graphemes.html)." -msgstr "" -"`String::chars` 會傳回實際字元的疊代器。請注意,由於[字形叢集](https://docs." -"rs/unicode-segmentation/latest/unicode_segmentation/struct.Graphemes.html)的" -"關係,`char` 和一般人所認為的「字元」可能不同。" - -#: src/std/string.md:33 -msgid "" -"When people refer to strings they could either be talking about `&str` or " -"`String`." -msgstr "提到字串時,一般人可能是指 `&str` 或 `String`。" - -#: src/std/string.md:34 -msgid "" -"When a type implements `Deref`, the compiler will let you " -"transparently call methods from `T`." -msgstr "" -"當型別實作 `Deref` 時,編譯器可讓您以公開透明的方式呼叫 `T` 中的" -"方法。" - -#: src/std/string.md:35 -msgid "" -"`String` implements `Deref` which transparently gives it " -"access to `str`'s methods." -msgstr "" -"`String` 會實作 `Deref`,後者能以公開透明的方式授予前者 `str` " -"方法的存取權。" - -#: src/std/string.md:36 -msgid "Write and compare `let s3 = s1.deref();` and `let s3 = &*s1`;." -msgstr "編寫及比較 `let s3 = s1.deref();` 和 `let s3 = &*s1`;。" - -#: src/std/string.md:37 -msgid "" -"`String` is implemented as a wrapper around a vector of bytes, many of the " -"operations you see supported on vectors are also supported on `String`, but " -"with some extra guarantees." -msgstr "" -"`String` 是以包裝函式的形式在位元組向量的四周實作,許多在向量上支援的作業也適" -"用於 `String`,但需要某些額外保證。" - -#: src/std/string.md:38 -msgid "Compare the different ways to index a `String`:" -msgstr "請比較各種為 `String` 建立索引的方法:" - -#: src/std/string.md:39 -msgid "" -"To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, " -"out-of-bounds." -msgstr "使用 `s3.chars().nth(i).unwrap()` 變為字元,其中 `i` 代表是否出界。" - -#: src/std/string.md:40 -msgid "" -"To a substring by using `s3[0..4]`, where that slice is on character " -"boundaries or not." -msgstr "使用 `s3[0..4]` 變為子字串,其中該切片會位於字元邊界上,也可能不會。" - -#: src/std/vec.md:1 -msgid "`Vec`" -msgstr "`Vec`" - -#: src/std/vec.md:3 -msgid "" -"[`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) is the standard " -"resizable heap-allocated buffer:" -msgstr "" -"[`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) 是可調整大小的標準" -"堆積配置緩衝區:" - -#: src/std/vec.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut v1 = Vec::new();\n" -" v1.push(42);\n" -" println!(\"v1: len = {}, capacity = {}\", v1.len(), v1.capacity());\n" -"\n" -" let mut v2 = Vec::with_capacity(v1.len() + 1);\n" -" v2.extend(v1.iter());\n" -" v2.push(9999);\n" -" println!(\"v2: len = {}, capacity = {}\", v2.len(), v2.capacity());\n" -"\n" -" // Canonical macro to initialize a vector with elements.\n" -" let mut v3 = vec![0, 0, 1, 2, 3, 4];\n" -"\n" -" // Retain only the even elements.\n" -" v3.retain(|x| x % 2 == 0);\n" -" println!(\"{v3:?}\");\n" -"\n" -" // Remove consecutive duplicates.\n" -" v3.dedup();\n" -" println!(\"{v3:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/std/vec.md:29 -msgid "" -"`Vec` implements [`Deref`](https://doc.rust-lang.org/std/vec/" -"struct.Vec.html#deref-methods-%5BT%5D), which means that you can call slice " -"methods on a `Vec`." -msgstr "" -"`Vec` 會實作 [`Deref`](https://doc.rust-lang.org/std/vec/" -"struct.Vec.html#deref-methods-%5BT%5D)。也就是說,您可以在 `Vec` 上呼叫切片方" -"法。" - -#: src/std/vec.md:37 -msgid "" -"`Vec` is a type of collection, along with `String` and `HashMap`. The data " -"it contains is stored on the heap. This means the amount of data doesn't " -"need to be known at compile time. It can grow or shrink at runtime." -msgstr "" -"`Vec` 是一種集合型別,與 `String` 和 `HashMap` 都一樣。`Vec` 內含的資料會儲存" -"在堆積上。這表示在編譯期間無需得知資料量,可在執行階段増量或減量。" - -#: src/std/vec.md:40 -msgid "" -"Notice how `Vec` is a generic type too, but you don't have to specify `T` " -"explicitly. As always with Rust type inference, the `T` was established " -"during the first `push` call." -msgstr "" -"請留意 `Vec` 也能做為泛型型別,但您不必明確指定 `T`。和往常的 Rust 型別推" -"論一樣,系統會在第一次 `push` 呼叫期間建立 `T`。" - -#: src/std/vec.md:42 -msgid "" -"`vec![...]` is a canonical macro to use instead of `Vec::new()` and it " -"supports adding initial elements to the vector." -msgstr "" -"`vec![...]` 是用於取代 `Vec::new()` 的標準巨集,且支援在向量中加入初始元素。" - -#: src/std/vec.md:44 -msgid "" -"To index the vector you use `[` `]`, but they will panic if out of bounds. " -"Alternatively, using `get` will return an `Option`. The `pop` function will " -"remove the last element." -msgstr "" -"如要為向量建立索引,請使用 `[` `]`,但如果超出範圍會引發恐慌。或者,使用 " -"`get` 則可傳回 `Option`。`pop` 函式會移除最後一個元素。" - -#: src/std/vec.md:46 -msgid "" -"Show iterating over a vector and mutating the value: `for e in &mut v { *e " -"+= 50; }`" -msgstr "示範如何對向量進行疊代並修改值:`for e in &mut v { *e += 50; }`" - -#: src/std/hashmap.md:1 src/bare-metal/no_std.md:46 -msgid "`HashMap`" -msgstr "`HashMap`" - -#: src/std/hashmap.md:3 -msgid "Standard hash map with protection against HashDoS attacks:" -msgstr "標準雜湊映射,可防範 HashDoS 攻擊:" - -#: src/std/hashmap.md:5 -msgid "" -"```rust,editable\n" -"use std::collections::HashMap;\n" -"\n" -"fn main() {\n" -" let mut page_counts = HashMap::new();\n" -" page_counts.insert(\"Adventures of Huckleberry Finn\".to_string(), " -"207);\n" -" page_counts.insert(\"Grimms' Fairy Tales\".to_string(), 751);\n" -" page_counts.insert(\"Pride and Prejudice\".to_string(), 303);\n" -"\n" -" if !page_counts.contains_key(\"Les Misérables\") {\n" -" println!(\"We know about {} books, but not Les Misérables.\",\n" -" page_counts.len());\n" -" }\n" -"\n" -" for book in [\"Pride and Prejudice\", \"Alice's Adventure in " -"Wonderland\"] {\n" -" match page_counts.get(book) {\n" -" Some(count) => println!(\"{book}: {count} pages\"),\n" -" None => println!(\"{book} is unknown.\")\n" -" }\n" -" }\n" -"\n" -" // Use the .entry() method to insert a value if nothing is found.\n" -" for book in [\"Pride and Prejudice\", \"Alice's Adventure in " -"Wonderland\"] {\n" -" let page_count: &mut i32 = page_counts.entry(book.to_string())." -"or_insert(0);\n" -" *page_count += 1;\n" -" }\n" -"\n" -" println!(\"{page_counts:#?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/std/hashmap.md:38 -msgid "" -"`HashMap` is not defined in the prelude and needs to be brought into scope." -msgstr "我們一開始並未定義 `HashMap`,因此現在需要將其納入課程範圍。" - -#: src/std/hashmap.md:39 -msgid "" -"Try the following lines of code. The first line will see if a book is in the " -"hashmap and if not return an alternative value. The second line will insert " -"the alternative value in the hashmap if the book is not found." -msgstr "" -"請嘗試使用以下幾行程式碼。第一行會查看書籍是否在雜湊表中,如果不在,系統會傳" -"回替代值。如果系統找不到書籍,第二行會在雜湊表中插入替代值。" - -#: src/std/hashmap.md:41 -msgid "" -"```rust,ignore\n" -" let pc1 = page_counts\n" -" .get(\"Harry Potter and the Sorcerer's Stone \")\n" -" .unwrap_or(&336);\n" -" let pc2 = page_counts\n" -" .entry(\"The Hunger Games\".to_string())\n" -" .or_insert(374);\n" -"```" -msgstr "" - -#: src/std/hashmap.md:49 -msgid "Unlike `vec!`, there is unfortunately no standard `hashmap!` macro." -msgstr "可惜的是,並沒有所謂標準的 `hashmap!` 巨集。這點與 `vec!` 不同。" - -#: src/std/hashmap.md:50 -msgid "" -"Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`](https://" -"doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#impl-" -"From%3C%5B(K,+V);+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E), which allows " -"us to easily initialize a hash map from a literal array:" -msgstr "" -"不過,自 Rust 1.56 起,HashMap 會實作 [`From<[(K, V); N]>`](https://doc.rust-" -"lang.org/std/collections/hash_map/struct.HashMap.html#impl-From%3C%5B(K,+V);" -"+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E),以便讓我們能從常值陣列初始化雜" -"湊映射:" - -#: src/std/hashmap.md:52 -msgid "" -"```rust,ignore\n" -" let page_counts = HashMap::from([\n" -" (\"Harry Potter and the Sorcerer's Stone\".to_string(), 336),\n" -" (\"The Hunger Games\".to_string(), 374),\n" -" ]);\n" -"```" -msgstr "" - -#: src/std/hashmap.md:59 -msgid "" -"Alternatively HashMap can be built from any `Iterator` which yields key-" -"value tuples." -msgstr "或者,您也可以透過任何能產生鍵/值元組的 `Iterator` 建立 HashMap。" - -#: src/std/hashmap.md:60 -msgid "" -"We are showing `HashMap`, and avoid using `&str` as key to make " -"examples easier. Using references in collections can, of course, be done, " -"but it can lead into complications with the borrow checker." -msgstr "" -"我們示範的是 `HashMap`,請避免使用 `&str 做為鍵,讓範例變得更簡" -"單。當然,也可以在集合中使用參照,但這可能會使借用檢查器變得複雜。" - -#: src/std/hashmap.md:62 -msgid "" -"Try removing `to_string()` from the example above and see if it still " -"compiles. Where do you think we might run into issues?" -msgstr "" -"請嘗試從上述範例中移除 `to_string()`,看看是否仍可編譯。您認為我們可能會在哪" -"裡遇到問題?" - -#: src/std/box.md:1 -msgid "`Box`" -msgstr "`Box`" - -#: src/std/box.md:3 -msgid "" -"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned " -"pointer to data on the heap:" -msgstr "" -"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) 是具有所有權的指" -"向堆積上的資料的指標:" - -#: src/std/box.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let five = Box::new(5);\n" -" println!(\"five: {}\", *five);\n" -"}\n" -"```" -msgstr "" - -#: src/std/box.md:13 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - -. .- - - - - - -.\n" -": : : :\n" -": five : : :\n" -": +-----+ : : +-----+ :\n" -": | o---|---+-----+-->| 5 | :\n" -": +-----+ : : +-----+ :\n" -": : : :\n" -": : : :\n" -"`- - - - - - -' `- - - - - - -'\n" -"```" -msgstr "" - -#: src/std/box.md:26 -msgid "" -"`Box` implements `Deref`, which means that you can [call " -"methods from `T` directly on a `Box`](https://doc.rust-lang.org/std/ops/" -"trait.Deref.html#more-on-deref-coercion)." -msgstr "" -"`Box` 會實作 `Deref`。也就是說,您可以[直接在 `Box` 上透過 " -"`T` 呼叫方法](https://doc.rust-lang.org/std/ops/trait.Deref.html#more-on-" -"deref-coercion)。" - -#: src/std/box.md:34 -msgid "" -"`Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be " -"not null. " -msgstr "" -"`Box` 就像是 C++ 中的 `std::unique_ptr`,兩者的差別在於 `Box` 不會是空值。" - -#: src/std/box.md:35 -msgid "" -"In the above example, you can even leave out the `*` in the `println!` " -"statement thanks to `Deref`. " -msgstr "上面的範例使用 `Deref`,因此 `println!` 陳述式甚至可以省略 `*`。" - -#: src/std/box.md:36 -msgid "A `Box` can be useful when you:" -msgstr "在以下情況下,您可以使用 `Box`:" - -#: src/std/box.md:37 -msgid "" -"have a type whose size that can't be known at compile time, but the Rust " -"compiler wants to know an exact size." -msgstr "編譯時遇到不知道大小為何的型別,但 Rust 編譯器需要知道確切大小。" - -#: src/std/box.md:38 -msgid "" -"want to transfer ownership of a large amount of data. To avoid copying large " -"amounts of data on the stack, instead store the data on the heap in a `Box` " -"so only the pointer is moved." -msgstr "" -"想要轉移大量資料的所有權。為避免在堆疊上複製大量資料,請改將資料儲存在 `Box` " -"的堆積上,這樣系統就只會移動指標。" - -#: src/std/box-recursive.md:1 -msgid "Box with Recursive Data Structures" -msgstr "包含遞迴資料結構的 Box" - -#: src/std/box-recursive.md:3 -msgid "" -"Recursive data types or data types with dynamic sizes need to use a `Box`:" -msgstr "遞迴資料型別或含有動態大小的資料型別必須使用 `Box`:" - -#: src/std/box-recursive.md:5 src/std/box-niche.md:3 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"enum List {\n" -" Cons(T, Box>),\n" -" Nil,\n" -"}\n" -"\n" -"fn main() {\n" -" let list: List = List::Cons(1, Box::new(List::Cons(2, Box::" -"new(List::Nil))));\n" -" println!(\"{list:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/std/box-recursive.md:18 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " -"- -.\n" -": : : :\n" -": " -"list : : :\n" -": +------+----+----+ : : +------+----+----+ +------+----+----" -"+ :\n" -": | Cons | 1 | o--+----+-----+--->| Cons | 2 | o--+--->| Nil | // | // " -"| :\n" -": +------+----+----+ : : +------+----+----+ +------+----+----" -"+ :\n" -": : : :\n" -": : : :\n" -"'- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - " -"- -'\n" -"```" -msgstr "" - -#: src/std/box-recursive.md:33 -msgid "" -"If the `Box` was not used here and we attempted to embed a `List` directly " -"into the `List`, the compiler would not compute a fixed size of the struct " -"in memory, it would look infinite." -msgstr "" -"如果這裡未使用 `Box`,且我們要將 `List` 直接嵌入 `List`,編譯器就不會計算出固" -"定的結構體記憶體大小,結構體看起來會像是無限大。" - -#: src/std/box-recursive.md:36 -msgid "" -"`Box` solves this problem as it has the same size as a regular pointer and " -"just points at the next element of the `List` in the heap." -msgstr "" -"`Box` 大小與一般指標相同,並且只會指向堆積中的下一個 `List` 元素,因此可以解" -"決這個問題。" - -#: src/std/box-recursive.md:39 -msgid "" -"Remove the `Box` in the List definition and show the compiler error. " -"\"Recursive with indirection\" is a hint you might want to use a Box or " -"reference of some kind, instead of storing a value directly." -msgstr "" -"將 `Box` 從 List 定義中移除後,畫面上會顯示編譯器錯誤。如果您看到「Recursive " -"with indirection」錯誤訊息,建議您使用 Box 或其他種類的參考,而不是直接儲存" -"值。" - -#: src/std/box-niche.md:16 -msgid "" -"A `Box` cannot be empty, so the pointer is always valid and non-`null`. This " -"allows the compiler to optimize the memory layout:" -msgstr "" -"`Box` 不能空白,因此指標會一律有效,而且不會是 `null`。這樣一來,編譯器可以將" -"記憶體配置最佳化:" - -#: src/std/box-niche.md:19 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " -"-.\n" -": : : :\n" -": " -"list : : :\n" -": +----+----+ : : +----+----+ +----+------" -"+ :\n" -": | 1 | o--+-----------+-----+--->| 2 | o--+--->| // | null " -"| :\n" -": +----+----+ : : +----+----+ +----+------" -"+ :\n" -": : : :\n" -": : : :\n" -"`- - - - - - - - - - - - -' '- - - - - - - - - - - - - - - - - - - - - - " -"-'\n" -"```" -msgstr "" - -#: src/std/rc.md:1 -msgid "`Rc`" -msgstr "`Rc`" - -#: src/std/rc.md:3 -msgid "" -"[`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) is a reference-" -"counted shared pointer. Use this when you need to refer to the same data " -"from multiple places:" -msgstr "" -"[`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) 是參考計數的共用指" -"標。如要在多個位置參考相同的資料,可以使用這個指標:" - -#: src/std/rc.md:6 -msgid "" -"```rust,editable\n" -"use std::rc::Rc;\n" -"\n" -"fn main() {\n" -" let mut a = Rc::new(10);\n" -" let mut b = Rc::clone(&a);\n" -"\n" -" println!(\"a: {a}\");\n" -" println!(\"b: {b}\");\n" -"}\n" -"```" -msgstr "" - -#: src/std/rc.md:18 +#: src/methods-and-traits/methods.md #, fuzzy msgid "" -"If you need to mutate the data inside an `Rc`, you will need to wrap the " -"data in a type such as [`Cell` or `RefCell`](../concurrency/shared_state/arc." -"md)." +"The `self` arguments specify the \"receiver\" - the object the method acts " +"on. There are several common receivers for a method:" msgstr "" -"如要在 `Rc` 內修改資料,必須將資料加入 [`Cell` 或 `RefCell`](../concurrency/" -"shared_state/arc.md) 等型別中。\\* 如果是多執行緒的環境,請參閱 [`Arc`]" -"(https://doc.rust-lang.org/std/sync/struct.Mutex.html)。\\* 您可以將共用指標" -"「降級」為 [`Weak`](https://doc.rust-lang.org/std/rc/struct.Weak.html) 指標," -"建立之後會捨棄的循環。" +"上述的 `&self` 表示方法會以不可變的方式借用物件。以下是其他可能的方法接收器:" -#: src/std/rc.md:20 +#: src/methods-and-traits/methods.md msgid "" -"See [`Arc`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) if you are " -"in a multi-threaded context." +"`&self`: borrows the object from the caller using a shared and immutable " +"reference. The object can be used again afterwards." msgstr "" +"`&self`:使用共用且不可變動的參照,從呼叫端借用物件。之後可以再次使用該物件。" -#: src/std/rc.md:19 +#: src/methods-and-traits/methods.md msgid "" -"You can _downgrade_ a shared pointer into a [`Weak`](https://doc.rust-lang." -"org/std/rc/struct.Weak.html) pointer to create cycles that will get dropped." +"`&mut self`: borrows the object from the caller using a unique and mutable " +"reference. The object can be used again afterwards." msgstr "" -"您可以將共用指標「降級」為 [`Weak`](https://doc.rust-lang.org/std/rc/struct." -"Weak.html) 指標,以便建立之後會捨棄的循環。" +"`&mut self`:使用不重複且可變動的參照,從呼叫端借用物件。之後可以再次使用該物" +"件。" -#: src/std/rc.md:31 +#: src/methods-and-traits/methods.md msgid "" -"`Rc`'s count ensures that its contained value is valid for as long as there " -"are references." -msgstr "`Rc` 的計數可確保只要有參考,內含的值就會保持有效。" +"`self`: takes ownership of the object and moves it away from the caller. The " +"method becomes the owner of the object. The object will be dropped " +"(deallocated) when the method returns, unless its ownership is explicitly " +"transmitted. Complete ownership does not automatically mean mutability." +msgstr "" +"`self`:取得物件擁有權,並將其移出呼叫端。方法會成為物件的擁有者。系統會在方" +"法傳回時捨棄物件 (取消分配),但如果其擁有權已明確傳送的情況例外。具備完整擁有" +"權,不自動等同於具備可變動性。" -#: src/std/rc.md:32 -msgid "Like C++'s `std::shared_ptr`." -msgstr "Rust 的 `Rc` 就好比是 C++ 的 `std::shared_ptr`。" +#: src/methods-and-traits/methods.md +#, fuzzy +msgid "`mut self`: same as above, but the method can mutate the object." +msgstr "`mut self`:同上,但方法可以變動物件。" -#: src/std/rc.md:33 +#: src/methods-and-traits/methods.md msgid "" -"`Rc::clone` is cheap: it creates a pointer to the same allocation and " -"increases the reference count. Does not make a deep clone and can generally " -"be ignored when looking for performance issues in code." +"No receiver: this becomes a static method on the struct. Typically used to " +"create constructors which are called `new` by convention." msgstr "" -"`Rc::clone` 的成本很低:這個做法會建立指向相同配置的指標,並增加參考計數,而" -"不會產生深克隆,尋找程式碼效能問題時通常可以忽略。" +"沒有接收器:這會成為結構體上的靜態方法,通常用於建立依慣例稱為 `new` 的建構函" +"式。" -#: src/std/rc.md:34 +#: src/methods-and-traits/methods.md +msgid "It can be helpful to introduce methods by comparing them to functions." +msgstr "導入方法時,若將方法比做函式,會很有幫助。" + +#: src/methods-and-traits/methods.md msgid "" -"`make_mut` actually clones the inner value if necessary (\"clone-on-write\") " -"and returns a mutable reference." +"Methods are called on an instance of a type (such as a struct or enum), the " +"first parameter represents the instance as `self`." msgstr "" -"`make_mut` 實際上會在必要時克隆內部值 (「clone-on-write」),並回傳可變動的參" -"考。" +"系統會在型別的執行個體 (例如結構體或列舉) 上呼叫方法,第一個參數以 `self` 代" +"表執行個體。" -#: src/std/rc.md:35 -msgid "Use `Rc::strong_count` to check the reference count." -msgstr "使用 `Rc::strong_count` 可查看參考計數。" - -#: src/std/rc.md:36 +#: src/methods-and-traits/methods.md msgid "" -"Compare the different datatypes mentioned. `Box` enables (im)mutable borrows " -"that are enforced at compile time. `RefCell` enables (im)mutable borrows " -"that are enforced at run time and will panic if it fails at runtime." +"Developers may choose to use methods to take advantage of method receiver " +"syntax and to help keep them more organized. By using methods we can keep " +"all the implementation code in one predictable place." msgstr "" -"比較提及的不同資料型別。`Box` 可啟用在編譯時強制執行的可變/不可變借用。" -"`RefCell` 可啟用在執行階段強制執行的可變/不可變借用,如果在執行階段失敗,將觸" -"發恐慌。" +"開發人員可以選擇透過方法來充分利用方法接收器語法,以更有條理的方式進行整理。" +"藉由使用方法,我們可以將所有實作程式碼存放在可預測的位置。" -#: src/std/rc.md:37 +#: src/methods-and-traits/methods.md +msgid "Point out the use of the keyword `self`, a method receiver." +msgstr "指出我們會使用關鍵字 `self`,也就是方法接收器。" + +#: src/methods-and-traits/methods.md msgid "" -"`Rc::downgrade` gives you a _weakly reference-counted_ object to create " -"cycles that will be dropped properly (likely in combination with `RefCell`)." -msgstr "" -"`Rc::downgrade` 提供的「弱參考計數」物件,建立之後會適當捨棄的循環 (可能會搭" -"配 `RefCell`)。" +"Show that it is an abbreviated term for `self: Self` and perhaps show how " +"the struct name could also be used." +msgstr "說明 `self` 是 `self: Self` 的縮寫,或許也能示範結構體名稱的可能用法。" -#: src/std/rc.md:41 +#: src/methods-and-traits/methods.md msgid "" -"```rust,editable\n" -"use std::rc::{Rc, Weak};\n" -"use std::cell::RefCell;\n" -"\n" -"#[derive(Debug)]\n" -"struct Node {\n" -" value: i64,\n" -" parent: Option>>,\n" -" children: Vec>>,\n" -"}\n" -"\n" -"fn main() {\n" -" let mut root = Rc::new(RefCell::new(Node {\n" -" value: 42,\n" -" parent: None,\n" -" children: vec![],\n" -" }));\n" -" let child = Rc::new(RefCell::new(Node {\n" -" value: 43,\n" -" children: vec![],\n" -" parent: Some(Rc::downgrade(&root))\n" -" }));\n" -" root.borrow_mut().children.push(child);\n" -"\n" -" println!(\"graph: {root:#?}\");\n" -"}\n" -"```" -msgstr "" +"Explain that `Self` is a type alias for the type the `impl` block is in and " +"can be used elsewhere in the block." +msgstr "講解 `Self` 是 `impl` 區塊所屬型別的型別別名,可用於該區塊的其他位置。" -#: src/modules.md:3 -msgid "We have seen how `impl` blocks let us namespace functions to a type." -msgstr "我們已介紹 `impl` 區塊如何讓我們將函式的命名空間建立為型別。" - -#: src/modules.md:5 -msgid "Similarly, `mod` lets us namespace types and functions:" -msgstr "同樣地,`mod` 可讓我們建立型別和函式的命名空間:" - -#: src/modules.md:7 +#: src/methods-and-traits/methods.md msgid "" -"```rust,editable\n" -"mod foo {\n" -" pub fn do_something() {\n" -" println!(\"In the foo module\");\n" -" }\n" -"}\n" -"\n" -"mod bar {\n" -" pub fn do_something() {\n" -" println!(\"In the bar module\");\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" foo::do_something();\n" -" bar::do_something();\n" -"}\n" -"```" +"Note how `self` is used like other structs and dot notation can be used to " +"refer to individual fields." msgstr "" +"提醒學員如何以類似於其他結構體的方式來使用 `self`,並指出點標記法可用來參照個" +"別欄位," -#: src/modules.md:28 +#: src/methods-and-traits/methods.md +#, fuzzy msgid "" -"Packages provide functionality and include a `Cargo.toml` file that " -"describes how to build a bundle of 1+ crates." +"This might be a good time to demonstrate how the `&self` differs from `self` " +"by trying to run `finish` twice." msgstr "" -"套件會提供功能,並收錄 `Cargo.toml` 檔案,用於說明如何建構含有超過 1 個 " -"Crate 的組合。" +"這可能是示範 `&self` 和 `self` 差異的好時機,您只要修改程式碼並嘗試執行 " +"say_hello 兩次即可。" -#: src/modules.md:29 +#: src/methods-and-traits/methods.md msgid "" -"Crates are a tree of modules, where a binary crate creates an executable and " -"a library crate compiles to a library." +"Beyond variants on `self`, there are also [special wrapper types](https://" +"doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be " +"receiver types, such as `Box`." msgstr "" -"Crate 是模組的樹狀結構,其中二進位檔 Crate 會建立執行檔,而程式庫 Crate 則會" -"編譯至程式庫。" +"除了 `self` 的變體以外,您還可以使用[特殊的包裝函式型別](https://doc.rust-" +"lang.org/reference/special-types-and-traits.html)做為接收器型別,例如 " +"`Box`。" -#: src/modules.md:30 -msgid "Modules define organization, scope, and are the focus of this section." -msgstr "模組不僅會定義組織、範圍,同時也是本節重點。" - -#: src/modules/visibility.md:3 -msgid "Modules are a privacy boundary:" -msgstr "我們可將模組視為隱私邊界:" - -#: src/modules/visibility.md:5 -msgid "Module items are private by default (hides implementation details)." -msgstr "模組項目預設為不公開 (會隱藏實作詳細資料)。" - -#: src/modules/visibility.md:6 -msgid "Parent and sibling items are always visible." -msgstr "父項和同層項目一律會顯示。" - -#: src/modules/visibility.md:7 +#: src/methods-and-traits/traits.md msgid "" -"In other words, if an item is visible in module `foo`, it's visible in all " -"the descendants of `foo`." -msgstr "換句話說,如果項目顯示在 `foo` 模組中,則會出現在 `foo` 的所有子系中。" +"Rust lets you abstract over types with traits. They're similar to interfaces:" +msgstr "Rust 可讓您依據特徵對型別進行抽象化處理,這與介面相似:" -#: src/modules/visibility.md:10 +#: src/methods-and-traits/traits.md +msgid "/// Return a sentence from this pet.\n" +msgstr "" + +#: src/methods-and-traits/traits.md +msgid "/// Print a string to the terminal greeting this pet.\n" +msgstr "" + +#: src/methods-and-traits/traits.md msgid "" -"```rust,editable\n" -"mod outer {\n" -" fn private() {\n" -" println!(\"outer::private\");\n" -" }\n" -"\n" -" pub fn public() {\n" -" println!(\"outer::public\");\n" -" }\n" -"\n" -" mod inner {\n" -" fn private() {\n" -" println!(\"outer::inner::private\");\n" -" }\n" -"\n" -" pub fn public() {\n" -" println!(\"outer::inner::public\");\n" -" super::private();\n" -" }\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" outer::public();\n" -"}\n" -"```" -msgstr "" +"A trait defines a number of methods that types must have in order to " +"implement the trait." +msgstr "特徵用於定義型別必須具有哪幾個方法,才能實作該特徵。" -#: src/modules/visibility.md:39 -msgid "Use the `pub` keyword to make modules public." -msgstr "使用 `pub` 關鍵字將模組設為公開。" - -#: src/modules/visibility.md:41 +#: src/methods-and-traits/traits.md msgid "" -"Additionally, there are advanced `pub(...)` specifiers to restrict the scope " -"of public visibility." -msgstr "此外,您也可以使用進階的 `pub(...)` 指定碼來限制公開的瀏覽權限範圍。" +"In the \"Generics\" segment, next, we will see how to build functionality " +"that is generic over all types implementing a trait." +msgstr "" -#: src/modules/visibility.md:43 +#: src/methods-and-traits/traits/implementing.md +#, fuzzy +msgid "Implementing Traits" +msgstr "實作不安全的特徵" + +#: src/methods-and-traits/traits/implementing.md +msgid "\"Oh you're a cutie! What's your name? {}\"" +msgstr "\"Oh you're a cutie! What's your name? {}\"" + +#: src/methods-and-traits/traits/implementing.md +#: src/smart-pointers/trait-objects.md +msgid "\"Woof, my name is {}!\"" +msgstr "\"Woof, my name is {}!\"" + +#: src/methods-and-traits/traits/implementing.md +#: src/smart-pointers/trait-objects.md +msgid "\"Fido\"" +msgstr "\"Fido\"" + +#: src/methods-and-traits/traits/implementing.md +#, fuzzy msgid "" -"See the [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-" -"privacy.html#pubin-path-pubcrate-pubsuper-and-pubself)." -msgstr "" -"請參閱 [Rust 參考資料](https://doc.rust-lang.org/reference/visibility-and-" -"privacy.html#pubin-path-pubcrate-pubsuper-and-pubself)。" +"To implement `Trait` for `Type`, you use an `impl Trait for Type { .. }` " +"block." +msgstr "特徵會在 `impl for { .. }` 區塊中實作。" -#: src/modules/visibility.md:44 -msgid "Configuring `pub(crate)` visibility is a common pattern." -msgstr "設定 `pub(crate)` 瀏覽權限是一種常見模式。" - -#: src/modules/visibility.md:45 -msgid "Less commonly, you can give visibility to a specific path." -msgstr "您也可以授予特定路徑的瀏覽權限,但這較不常見。" - -#: src/modules/visibility.md:46 +#: src/methods-and-traits/traits/implementing.md msgid "" -"In any case, visibility must be granted to an ancestor module (and all of " -"its descendants)." -msgstr "無論如何,都請務必將瀏覽權限授予祖系模組 (及其所有子系)。" +"Unlike Go interfaces, just having matching methods is not enough: a `Cat` " +"type with a `talk()` method would not automatically satisfy `Pet` unless it " +"is in an `impl Pet` block." +msgstr "" -#: src/modules/paths.md:3 -msgid "Paths are resolved as follows:" -msgstr "路徑的解析方式包括:" - -#: src/modules/paths.md:5 -msgid "As a relative path:" -msgstr "做為相對路徑:" - -#: src/modules/paths.md:6 -msgid "`foo` or `self::foo` refers to `foo` in the current module," -msgstr "`foo` 或 `self::foo` 是指目前模組中的 `foo`。" - -#: src/modules/paths.md:7 -msgid "`super::foo` refers to `foo` in the parent module." -msgstr "`super::foo` 是指父項模組中的 `foo`。" - -#: src/modules/paths.md:9 -msgid "As an absolute path:" -msgstr "做為絕對路徑:" - -#: src/modules/paths.md:10 -msgid "`crate::foo` refers to `foo` in the root of the current crate," -msgstr "`crate::foo` 是指目前 Crate 根目錄中的 `foo`。" - -#: src/modules/paths.md:11 -msgid "`bar::foo` refers to `foo` in the `bar` crate." -msgstr "`bar::foo` 是指 `bar` Crate 中的 `foo`。" - -#: src/modules/paths.md:13 +#: src/methods-and-traits/traits/implementing.md msgid "" -"A module can bring symbols from another module into scope with `use`. You " -"will typically see something like this at the top of each module:" +"Traits may provide default implementations of some methods. Default " +"implementations can rely on all the methods of the trait. In this case, " +"`greet` is provided, and relies on `talk`." msgstr "" -"模組可以使用 `use` 將其他模組的符號帶進範圍內。您通常會在每個模組的頂端看到類" -"似下方的內容:" -#: src/modules/paths.md:16 +#: src/methods-and-traits/traits/associated-types.md msgid "" -"```rust,editable\n" -"use std::collections::HashSet;\n" -"use std::mem::transmute;\n" -"```" +"Associated types allow are placeholder types which are filled in by the " +"trait implementation." msgstr "" -#: src/modules/filesystem.md:3 -msgid "The module content can be omitted:" -msgstr "" - -#: src/modules/filesystem.md:5 +#: src/methods-and-traits/traits/associated-types.md msgid "" -"```rust,editable,compile_fail\n" -"mod garden;\n" -"```" +"Associated types are sometimes also called \"output types\". The key " +"observation is that the implementer, not the caller, chooses this type." msgstr "" -#: src/modules/filesystem.md:9 -msgid "The `garden` module content is found at:" -msgstr "" - -#: src/modules/filesystem.md:11 -msgid "`src/garden.rs` (modern Rust 2018 style)" -msgstr "" - -#: src/modules/filesystem.md:12 -msgid "`src/garden/mod.rs` (older Rust 2015 style)" -msgstr "" - -#: src/modules/filesystem.md:14 -msgid "Similarly, a `garden::vegetables` module can be found at:" -msgstr "" - -#: src/modules/filesystem.md:16 -msgid "`src/garden/vegetables.rs` (modern Rust 2018 style)" -msgstr "" - -#: src/modules/filesystem.md:17 -msgid "`src/garden/vegetables/mod.rs` (older Rust 2015 style)" -msgstr "" - -#: src/modules/filesystem.md:12 -msgid "The `crate` root is in:" -msgstr "`crate` 根層級位於:" - -#: src/modules/filesystem.md:14 -msgid "`src/lib.rs` (for a library crate)" -msgstr "`src/lib.rs` (適用於程式庫 Crate)" - -#: src/modules/filesystem.md:15 -msgid "`src/main.rs` (for a binary crate)" -msgstr "`src/main.rs` (適用於二進位檔 Crate)" - -#: src/modules/filesystem.md:17 +#: src/methods-and-traits/traits/associated-types.md msgid "" -"Modules defined in files can be documented, too, using \"inner doc " -"comments\". These document the item that contains them -- in this case, a " -"module." -msgstr "" -"您也可以使用 \"inner doc comments\" 記錄檔案中定義的模組。這些會記錄包含它們" -"的項目,在本例中就是模組。" - -#: src/modules/filesystem.md:27 -msgid "" -"```rust,editable,compile_fail\n" -"//! This module implements the garden, including a highly performant " -"germination\n" -"//! implementation.\n" -"\n" -"// Re-export types from this module.\n" -"pub use seeds::SeedPacket;\n" -"pub use garden::Garden;\n" -"\n" -"/// Sow the given seed packets.\n" -"pub fn sow(seeds: Vec) { todo!() }\n" -"\n" -"/// Harvest the produce in the garden that is ready.\n" -"pub fn harvest(garden: &mut Garden) { todo!() }\n" -"```" +"Many standard library traits have associated types, including arithmetic " +"operators and `Iterator`." msgstr "" -#: src/modules/filesystem.md:44 +#: src/methods-and-traits/deriving.md msgid "" -"The change from `module/mod.rs` to `module.rs` doesn't preclude the use of " -"submodules in Rust 2018. (It was mandatory in Rust 2015.)" +"Supported traits can be automatically implemented for your custom types, as " +"follows:" +msgstr "系統會自動為您的自訂型別實作支援的特徵,如下所示:" + +#: src/methods-and-traits/deriving.md +msgid "// Default trait adds `default` constructor.\n" +msgstr "// Default trait adds `default` constructor.\n" + +#: src/methods-and-traits/deriving.md +msgid "// Clone trait adds `clone` method.\n" +msgstr "// Clone trait adds `clone` method.\n" + +#: src/methods-and-traits/deriving.md +msgid "\"EldurScrollz\"" +msgstr "\"EldurScrollz\"" + +#: src/methods-and-traits/deriving.md +msgid "// Debug trait adds support for printing with `{:?}`.\n" +msgstr "// Debug trait adds support for printing with `{:?}`.\n" + +#: src/methods-and-traits/deriving.md +msgid "\"{:?} vs. {:?}\"" +msgstr "\"{:?} vs. {:?}\"" + +#: src/methods-and-traits/deriving.md +msgid "" +"Derivation is implemented with macros, and many crates provide useful derive " +"macros to add useful functionality. For example, `serde` can derive " +"serialization support for a struct using `#[derive(Serialize)]`." msgstr "" +"衍生會透過巨集實作,許多 Crate 都提供實用的衍生巨集,以便新增實用功能。例如," +"`serde` 可以使用 `#[derive(Serialize)]`,為結構體衍生序列化支援。" -#: src/modules/filesystem.md:47 -msgid "The following is valid:" +#: src/methods-and-traits/exercise.md +msgid "" +"Let's design a simple logging utility, using a trait `Logger` with a `log` " +"method. Code which might log its progress can then take an `&impl Logger`. " +"In testing, this might put messages in the test logfile, while in a " +"production build it would send messages to a log server." msgstr "" +"我們來設計一個簡單的記錄公用程式,使用 `Logger` 特徵搭配 `log` 方法。如果程式" +"碼可能會記錄相關進度,就可以採用 `&impl Logger`。在測試過程中,這可能會將訊息" +"置於測試記錄檔中;而在實際版本中,則會將訊息傳送至記錄伺服器。" -#: src/modules/filesystem.md:49 +#: src/methods-and-traits/exercise.md msgid "" -"```ignore\n" -"src/\n" -"├── main.rs\n" -"├── top_module.rs\n" -"└── top_module/\n" -" └── sub_module.rs\n" -"```" +"However, the `StderrLogger` given below logs all messages, regardless of " +"verbosity. Your task is to write a `VerbosityFilter` type that will ignore " +"messages above a maximum verbosity." msgstr "" +"不過,下方的 `StderrLogger` 會記錄詳細程度不限的所有訊息。您的任務是編寫 " +"`VerbosityFilter` 型別,忽略超出詳細程度上限的訊息。" -#: src/modules/filesystem.md:57 +#: src/methods-and-traits/exercise.md msgid "" -"The main reason for the change is to prevent many files named `mod.rs`, " -"which can be hard to distinguish in IDEs." +"This is a common pattern: a struct wrapping a trait implementation and " +"implementing that same trait, adding behavior in the process. What other " +"kinds of wrappers might be useful in a logging utility?" msgstr "" +"以下是常見模式:結構體包裝一個特徵實作項目,並實作該相同特徵,在程序中加入行" +"為。想一想,還有哪些其他類型的包裝函式可能在記錄公用程式中派上用場?" -#: src/modules/filesystem.md:60 +#: src/methods-and-traits/exercise.md src/methods-and-traits/solution.md +msgid "/// Log a message at the given verbosity level.\n" +msgstr "/// Log a message at the given verbosity level.\n" + +#: src/methods-and-traits/exercise.md src/methods-and-traits/solution.md +msgid "\"verbosity={verbosity}: {message}\"" +msgstr "\"verbosity={verbosity}: {message}\"" + +#: src/methods-and-traits/exercise.md src/methods-and-traits/solution.md +msgid "\"FYI\"" +msgstr "\"FYI\"" + +#: src/methods-and-traits/exercise.md src/methods-and-traits/solution.md +msgid "\"Uhoh\"" +msgstr "\"Uhoh\"" + +#: src/methods-and-traits/exercise.md +msgid "// TODO: Define and implement `VerbosityFilter`.\n" +msgstr "// TODO: Define and implement `VerbosityFilter`.\n" + +#: src/methods-and-traits/solution.md +msgid "/// Only log messages up to the given verbosity level.\n" +msgstr "/// Only log messages up to the given verbosity level.\n" + +#: src/generics.md +msgid "[Generic Functions](./generics/generic-functions.md) (5 minutes)" +msgstr "[泛型函式](./generics/generic-functions.md) (5 分鐘)" + +#: src/generics.md +msgid "[Generic Data Types](./generics/generic-data.md) (10 minutes)" +msgstr "[泛型資料型別](./generics/generic-data.md) (10 分鐘)" + +#: src/generics.md +msgid "[Trait Bounds](./generics/trait-bounds.md) (10 minutes)" +msgstr "[特徵界線](./generics/trait-bounds.md) (10 分鐘)" + +#: src/generics.md +msgid "[impl Trait](./generics/impl-trait.md) (5 minutes)" +msgstr "[impl 特徵](./generics/impl-trait.md) (5 分鐘)" + +#: src/generics.md +msgid "[Exercise: Generic min](./generics/exercise.md) (10 minutes)" +msgstr "[練習:泛型 min](./generics/exercise.md) (10 分鐘)" + +#: src/generics/generic-functions.md +#, fuzzy msgid "" -"Rust will look for modules in `modulename/mod.rs` and `modulename.rs`, but " -"this can be changed with a compiler directive:" -msgstr "" - -#: src/modules/filesystem.md:63 -msgid "" -"```rust,ignore\n" -"#[path = \"some/path.rs\"]\n" -"mod some_module { }\n" -"```" -msgstr "" - -#: src/modules/filesystem.md:59 -msgid "" -"This is useful, for example, if you would like to place tests for a module " -"in a file named `some_module_test.rs`, similar to the convention in Go." -msgstr "" -"舉例來說,如果您想將模組的測試放在名為 `some_module_test.rs` 的檔案中 (類似 " -"Go 中的慣例),這就會很實用。" - -#: src/exercises/day-2/afternoon.md:1 -msgid "Day 2: Afternoon Exercises" -msgstr "第 2 天:下午練習" - -#: src/exercises/day-2/afternoon.md:3 -msgid "The exercises for this afternoon will focus on strings and iterators." -msgstr "今天下午的練習著重在字串和疊代器。" - -#: src/exercises/day-1/luhn.md:3 -msgid "" -"The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used " -"to validate credit card numbers. The algorithm takes a string as input and " -"does the following to validate the credit card number:" -msgstr "" -"[盧恩演算法](https://en.wikipedia.org/wiki/Luhn_algorithm)可用於驗證信用卡號" -"碼。這個演算法會將字串做為輸入內容,並執行下列操作來驗證信用卡號碼:" - -#: src/exercises/day-1/luhn.md:7 -msgid "Ignore all spaces. Reject number with less than two digits." -msgstr "忽略所有空格。拒絕少於兩位數的號碼。" - -#: src/exercises/day-2/luhn.md:9 -msgid "" -"Moving from right to left, double every second digit: for the number `1234`, " -"we double `3` and `1`." -msgstr "" - -#: src/exercises/day-2/luhn.md:12 -msgid "" -"After doubling a digit, sum the digits. So doubling `7` becomes `14` which " -"becomes `5`." -msgstr "" - -#: src/exercises/day-1/luhn.md:15 -msgid "Sum all the undoubled and doubled digits." -msgstr "將所有數字 (無論是否已乘二) 相加。" - -#: src/exercises/day-1/luhn.md:17 -msgid "The credit card number is valid if the sum ends with `0`." -msgstr "如果加總所得數字的末位是 `0`,代表信用卡卡號有效。" - -#: src/exercises/day-2/luhn.md:19 -msgid "" -"Copy the following code to and implement the " -"function:" -msgstr "" - -#: src/exercises/day-2/luhn.md:23 -msgid "" -"```rust\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"pub fn luhn(cc_number: &str) -> bool {\n" -" unimplemented!()\n" -"}\n" -"\n" -"#[test]\n" -"fn test_non_digit_cc_number() {\n" -" assert!(!luhn(\"foo\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_empty_cc_number() {\n" -" assert!(!luhn(\"\"));\n" -" assert!(!luhn(\" \"));\n" -" assert!(!luhn(\" \"));\n" -" assert!(!luhn(\" \"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_single_digit_cc_number() {\n" -" assert!(!luhn(\"0\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_two_digit_cc_number() {\n" -" assert!(luhn(\" 0 0 \"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_valid_cc_number() {\n" -" assert!(luhn(\"4263 9826 4026 9299\"));\n" -" assert!(luhn(\"4539 3195 0343 6467\"));\n" -" assert!(luhn(\"7992 7398 713\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_invalid_cc_number() {\n" -" assert!(!luhn(\"4223 9826 4026 9299\"));\n" -" assert!(!luhn(\"4539 3195 0343 6476\"));\n" -" assert!(!luhn(\"8273 1232 7352 0569\"));\n" -"}\n" -"\n" -"#[allow(dead_code)]\n" -"fn main() {}\n" -"```" -msgstr "" - -#: src/exercises/day-2/strings-iterators.md:3 -msgid "" -"In this exercise, you are implementing a routing component of a web server. " -"The server is configured with a number of _path prefixes_ which are matched " -"against _request paths_. The path prefixes can contain a wildcard character " -"which matches a full segment. See the unit tests below." -msgstr "" -"在本次練習中,您將實作網路伺服器的路由元件。伺服器設定了多個與「要求路徑」__" -"相符的「路徑前置字元」__。路徑前置字元可包含與完整片段相符的萬用字元。請參閱" -"下方的單元測試。" - -#: src/exercises/day-2/strings-iterators.md:8 -msgid "" -"Copy the following code to and make the tests " -"pass. Try avoiding allocating a `Vec` for your intermediate results:" -msgstr "" -"將下列程式碼複製到 ,然後設法通過測試。請盡量避" -"免為中繼結果分配 `Vec`:" - -#: src/exercises/day-2/strings-iterators.md:12 -msgid "" -"```rust\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_variables, dead_code)]\n" -"\n" -"pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {\n" -" unimplemented!()\n" -"}\n" -"\n" -"#[test]\n" -"fn test_matches_without_wildcard() {\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers\"));\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/" -"abc-123\"));\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/abc/" -"books\"));\n" -"\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1\"));\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/publishersBooks\"));\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/parent/" -"publishers\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_matches_with_wildcard() {\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/books\"\n" -" ));\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/bar/books\"\n" -" ));\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/books/book1\"\n" -" ));\n" -"\n" -" assert!(!prefix_matches(\"/v1/publishers/*/books\", \"/v1/" -"publishers\"));\n" -" assert!(!prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/booksByAuthor\"\n" -" ));\n" -"}\n" -"```" -msgstr "" - -#: src/welcome-day-3.md:1 -msgid "Welcome to Day 3" -msgstr "歡迎參加第 3 天課程" - -#: src/welcome-day-3.md:3 -msgid "Today, we will cover some more advanced topics of Rust:" -msgstr "今天我們會探討一些有關 Rust 的進階主題:" - -#: src/welcome-day-3.md:5 -msgid "" -"Traits: deriving traits, default methods, and important standard library " -"traits." -msgstr "特徵:衍生特徵、預設方法,以及重要的標準程式庫特徵。" - -#: src/welcome-day-3.md:8 -msgid "" -"Generics: generic data types, generic methods, monomorphization, and trait " -"objects." -msgstr "泛型:泛型資料型別、泛型方法、單型,以及特徵物件。" - -#: src/welcome-day-3.md:11 -msgid "Error handling: panics, `Result`, and the try operator `?`." -msgstr "錯誤處理:恐慌、`Result`,以及 try 運算子 `?`。" - -#: src/welcome-day-3.md:13 -msgid "Testing: unit tests, documentation tests, and integration tests." -msgstr "測試:單元測試、說明文件測試,以及整合測試。" - -#: src/welcome-day-3.md:15 -msgid "" -"Unsafe Rust: raw pointers, static variables, unsafe functions, and extern " -"functions." -msgstr "不安全的 Rust:原始指標、靜態變數、不安全的函式,以及 extern 函式。" - -#: src/generics.md:3 -msgid "" -"Rust support generics, which lets you abstract an algorithm (such as " -"sorting) over the types used in the algorithm." +"Rust supports generics, which lets you abstract algorithms or data " +"structures (such as sorting or a binary tree) over the types used or stored." msgstr "" "Rust 支援泛型 (Generics),因此可以將一個演算法 (例如:排序) 抽象化而不需要依" "賴特定型別。" -#: src/generics/data-types.md:3 +#: src/generics/generic-functions.md +msgid "/// Pick `even` or `odd` depending on the value of `n`.\n" +msgstr "/// Pick `even` or `odd` depending on the value of `n`.\n" + +#: src/generics/generic-functions.md +msgid "\"picked a number: {:?}\"" +msgstr "\"picked a number: {:?}\"" + +#: src/generics/generic-functions.md +msgid "\"picked a tuple: {:?}\"" +msgstr "\"picked a tuple: {:?}\"" + +#: src/generics/generic-functions.md +msgid "\"dog\"" +msgstr "\"dog\"" + +#: src/generics/generic-functions.md +msgid "\"cat\"" +msgstr "\"cat\"" + +#: src/generics/generic-functions.md +msgid "" +"Rust infers a type for T based on the types of the arguments and return " +"value." +msgstr "Rust 會根據引數型別和傳回的值來推斷 T 的型別。" + +#: src/generics/generic-functions.md +msgid "" +"This is similar to C++ templates, but Rust partially compiles the generic " +"function immediately, so that function must be valid for all types matching " +"the constraints. For example, try modifying `pick` to return `even + odd` if " +"`n == 0`. Even if only the `pick` instantiation with integers is used, Rust " +"still considers it invalid. C++ would let you do this." +msgstr "" +"這與 C++ 模板 (template) 類似,但 Rust 會立即對泛型函式進行部分編譯,因此函式" +"必須適用於所有符合限制條件的型別。舉例來說,如果 `n == 0`,請嘗試修改 `pick` " +"以傳回 `even + odd`。即使只使用具有整數的 `pick` 建立例項,Rust 仍會將其視為" +"無效。但 C++ 就能讓您這麼做。" + +#: src/generics/generic-functions.md +#, fuzzy +msgid "" +"Generic code is turned into non-generic code based on the call sites. This " +"is a zero-cost abstraction: you get exactly the same result as if you had " +"hand-coded the data structures without the abstraction." +msgstr "" +"這是一種零成本抽象:單型化的結果,等同於不使用抽象化並手動寫出資料結構的實際" +"型別。" + +#: src/generics/generic-data.md msgid "You can use generics to abstract over the concrete field type:" msgstr "你可以使用泛型將具體的欄位型別抽象化:" -#: src/generics/data-types.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point {\n" -" x: T,\n" -" y: T,\n" -"}\n" -"\n" -"fn main() {\n" -" let integer = Point { x: 5, y: 10 };\n" -" let float = Point { x: 1.0, y: 4.0 };\n" -" println!(\"{integer:?} and {float:?}\");\n" -"}\n" -"```" -msgstr "" +#: src/generics/generic-data.md +msgid "// fn set_x(&mut self, x: T)\n" +msgstr "// fn set_x(&mut self, x: T)\n" -#: src/generics/data-types.md:21 -msgid "Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`." -msgstr "試著宣告一個新的變數 `let p = Point { x: 5, y: 10.0 };`." +#: src/generics/generic-data.md +msgid "\"{integer:?} and {float:?}\"" +msgstr "\"{integer:?} and {float:?}\"" -#: src/generics/data-types.md:23 -msgid "Fix the code to allow points that have elements of different types." -msgstr "修改程式碼,讓 points 能擁有不同型別的元素。" +#: src/generics/generic-data.md +msgid "\"coords: {:?}\"" +msgstr "\"coords: {:?}\"" -#: src/generics/methods.md:3 -msgid "You can declare a generic type on your `impl` block:" -msgstr "你可以將 `impl` 區塊宣告為泛型型別:" - -#: src/generics/methods.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug)]\n" -"struct Point(T, T);\n" -"\n" -"impl Point {\n" -" fn x(&self) -> &T {\n" -" &self.0 // + 10\n" -" }\n" -"\n" -" // fn set_x(&mut self, x: T)\n" -"}\n" -"\n" -"fn main() {\n" -" let p = Point(5, 10);\n" -" println!(\"p.x = {}\", p.x());\n" -"}\n" -"```" -msgstr "" - -#: src/generics/methods.md:25 +#: src/generics/generic-data.md msgid "" "_Q:_ Why `T` is specified twice in `impl Point {}`? Isn't that " "redundant?" msgstr "_問題:_ 為什麼 `T` 在 `impl Point {}` 中重複出現了兩次?" -#: src/generics/methods.md:26 +#: src/generics/generic-data.md msgid "" "This is because it is a generic implementation section for generic type. " "They are independently generic." @@ -9369,15 +5902,16 @@ msgstr "" "因為這是一個泛型型別 `T` 的 `Point` 實作,而 `Point` 的型別為泛型 `T`。它們是" "各自獨立的泛型。" -#: src/generics/methods.md:27 +#: src/generics/generic-data.md msgid "It means these methods are defined for any `T`." msgstr "這表示這個方法是為了任意型別 `T` 而定義的。" -#: src/generics/methods.md:28 -msgid "It is possible to write `impl Point { .. }`. " +#: src/generics/generic-data.md +#, fuzzy +msgid "It is possible to write `impl Point { .. }`." msgstr "你可以寫成 `impl Point { .. }`。" -#: src/generics/methods.md:29 +#: src/generics/generic-data.md msgid "" "`Point` is still generic and you can use `Point`, but methods in this " "block will only be available for `Point`." @@ -9385,420 +5919,55 @@ msgstr "" "由於 `Point` 仍然是泛型型別,你可以使用 `Point`,但這個方法將只適用於 " "`Point`。" -#: src/generics/monomorphization.md:3 -msgid "Generic code is turned into non-generic code based on the call sites:" -msgstr "" -"Rust 在編譯時進行單型化 (Monomorphization),根據不同呼叫者,將泛型程式碼轉換" -"成實際型別的程式碼:" - -#: src/generics/monomorphization.md:5 +#: src/generics/generic-data.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let integer = Some(5);\n" -" let float = Some(5.0);\n" -"}\n" -"```" +"Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`. Update the " +"code to allow points that have elements of different types, by using two " +"type variables, e.g., `T` and `U`." msgstr "" +"請嘗試宣告新變數 `let p = Point { x: 5, y: 10.0 };`。您可以使用兩種型別變數來" +"更新程式碼,允許含有不同型別元素的點,例如:`T` 和 `U`。" -#: src/generics/monomorphization.md:12 -msgid "behaves as if you wrote" -msgstr "以上程式碼等同於下方的程式碼" - -#: src/generics/monomorphization.md:14 -msgid "" -"```rust,editable\n" -"enum Option_i32 {\n" -" Some(i32),\n" -" None,\n" -"}\n" -"\n" -"enum Option_f64 {\n" -" Some(f64),\n" -" None,\n" -"}\n" -"\n" -"fn main() {\n" -" let integer = Option_i32::Some(5);\n" -" let float = Option_f64::Some(5.0);\n" -"}\n" -"```" -msgstr "" - -#: src/generics/monomorphization.md:31 -msgid "" -"This is a zero-cost abstraction: you get exactly the same result as if you " -"had hand-coded the data structures without the abstraction." -msgstr "" -"這是一種零成本抽象:單型化的結果,等同於不使用抽象化並手動寫出資料結構的實際" -"型別。" - -#: src/traits.md:3 -msgid "" -"Rust lets you abstract over types with traits. They're similar to interfaces:" -msgstr "Rust 可讓您依據特徵對型別進行抽象化處理,這與介面相似:" - -#: src/traits.md:5 -msgid "" -"```rust,editable\n" -"trait Pet {\n" -" fn name(&self) -> String;\n" -"}\n" -"\n" -"struct Dog {\n" -" name: String,\n" -"}\n" -"\n" -"struct Cat;\n" -"\n" -"impl Pet for Dog {\n" -" fn name(&self) -> String {\n" -" self.name.clone()\n" -" }\n" -"}\n" -"\n" -"impl Pet for Cat {\n" -" fn name(&self) -> String {\n" -" String::from(\"The cat\") // No name, cats won't respond to it " -"anyway.\n" -" }\n" -"}\n" -"\n" -"fn greet(pet: &P) {\n" -" println!(\"Who's a cutie? {} is!\", pet.name());\n" -"}\n" -"\n" -"fn main() {\n" -" let fido = Dog { name: \"Fido\".into() };\n" -" greet(&fido);\n" -"\n" -" let captain_floof = Cat;\n" -" greet(&captain_floof);\n" -"}\n" -"```" -msgstr "" - -#: src/traits/trait-objects.md:3 -msgid "" -"Trait objects allow for values of different types, for instance in a " -"collection:" -msgstr "特徵物件可接受不同型別的值,舉例來說,在集合中會是這樣:" - -#: src/traits/trait-objects.md:5 -msgid "" -"```rust,editable\n" -"trait Pet {\n" -" fn name(&self) -> String;\n" -"}\n" -"\n" -"struct Dog {\n" -" name: String,\n" -"}\n" -"\n" -"struct Cat;\n" -"\n" -"impl Pet for Dog {\n" -" fn name(&self) -> String {\n" -" self.name.clone()\n" -" }\n" -"}\n" -"\n" -"impl Pet for Cat {\n" -" fn name(&self) -> String {\n" -" String::from(\"The cat\") // No name, cats won't respond to it " -"anyway.\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let pets: Vec> = vec![\n" -" Box::new(Cat),\n" -" Box::new(Dog { name: String::from(\"Fido\") }),\n" -" ];\n" -" for pet in pets {\n" -" println!(\"Hello {}!\", pet.name());\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/traits/trait-objects.md:40 -msgid "Memory layout after allocating `pets`:" -msgstr "以下是配置 `pets` 後的記憶體配置:" - -#: src/traits/trait-objects.md:42 -msgid "" -"```bob\n" -" Stack Heap\n" -".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - " -"- -.\n" -": : : :\n" -": " -"pets : : :\n" -": +-----------+-------+ : : +-----+-----" -"+ :\n" -": | ptr | o---+---+-----+-->| o o | o o " -"| :\n" -": | len | 2 | : : +-|-|-+-|-|-" -"+ :\n" -": | capacity | 2 | : : | | | | +---------------" -"+ :\n" -": +-----------+-------+ : : | | | '-->| name: \"Fido\" " -"| :\n" -": : : | | | +---------------" -"+ :\n" -"`- - - - - - - - - - - - - -' : | | " -"| :\n" -" : | | | +----------------------" -"+ : \n" -" : | | '---->| \"::name\" " -"| :\n" -" : | | +----------------------" -"+ : \n" -" : | " -"| : \n" -" : | | +-" -"+ : \n" -" : | '-->|" -"\\| : \n" -" : | +-" -"+ : \n" -" : " -"| : \n" -" : | +----------------------" -"+ : \n" -" : '---->| \"::name\" " -"| : \n" -" : +----------------------" -"+ :\n" -" : :\n" -" '- - - - - - - - - - - - - - - - - - - - - " -"- -'\n" -"\n" -"```" -msgstr "" - -#: src/traits/trait-objects.md:72 -msgid "" -"Types that implement a given trait may be of different sizes. This makes it " -"impossible to have things like `Vec` in the example above." -msgstr "" -"如果型別會實作特定特徵,大小可能會不同。因此在上例中就不可能出現 `Vec` " -"這類項目。" - -#: src/traits/trait-objects.md:73 -msgid "" -"`dyn Pet` is a way to tell the compiler about a dynamically sized type that " -"implements `Pet`." -msgstr "可透過 `dyn Pet` 這個方法向編譯器告知實作 `Pet` 的動態大小型別。" - -#: src/traits/trait-objects.md:74 -msgid "" -"In the example, `pets` holds _fat pointers_ to objects that implement `Pet`. " -"The fat pointer consists of two components, a pointer to the actual object " -"and a pointer to the virtual method table for the `Pet` implementation of " -"that particular object." -msgstr "" -"在本例中,`pets` 會保留指向物件的「虛指標」__,而物件會實作 `Pet`。虛指標包含" -"兩個元件,指向實際物件的指標,以及指向該特定物件中 `Pet` 實作項目的虛擬方法表" -"格。" - -#: src/traits/trait-objects.md:75 -msgid "Compare these outputs in the above example:" -msgstr "比較上述範例的輸出內容:" - -#: src/traits/trait-objects.md:76 -msgid "" -"```rust,ignore\n" -" println!(\"{} {}\", std::mem::size_of::(), std::mem::size_of::" -"());\n" -" println!(\"{} {}\", std::mem::size_of::<&Dog>(), std::mem::size_of::" -"<&Cat>());\n" -" println!(\"{}\", std::mem::size_of::<&dyn Pet>());\n" -" println!(\"{}\", std::mem::size_of::>());\n" -"```" -msgstr "" - -#: src/traits/deriving-traits.md:3 -msgid "You can let the compiler derive a number of traits:" -msgstr "您可以讓編譯器衍生多種特徵:" - -#: src/traits/deriving-traits.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug, Clone, PartialEq, Eq, Default)]\n" -"struct Player {\n" -" name: String,\n" -" strength: u8,\n" -" hit_points: u8,\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Player::default();\n" -" let p2 = p1.clone();\n" -" println!(\"Is {:?}\\nequal to {:?}?\\nThe answer is {}!\", &p1, &p2,\n" -" if p1 == p2 { \"yes\" } else { \"no\" });\n" -"}\n" -"```" -msgstr "" - -#: src/traits/default-methods.md:3 -msgid "Traits can implement behavior in terms of other trait methods:" -msgstr "特徵可以依照其他特徵方法來實作行為:" - -#: src/traits/default-methods.md:5 -msgid "" -"```rust,editable\n" -"trait Equals {\n" -" fn equal(&self, other: &Self) -> bool;\n" -" fn not_equal(&self, other: &Self) -> bool {\n" -" !self.equal(other)\n" -" }\n" -"}\n" -"\n" -"#[derive(Debug)]\n" -"struct Centimeter(i16);\n" -"\n" -"impl Equals for Centimeter {\n" -" fn equal(&self, other: &Centimeter) -> bool {\n" -" self.0 == other.0\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let a = Centimeter(10);\n" -" let b = Centimeter(20);\n" -" println!(\"{a:?} equals {b:?}: {}\", a.equal(&b));\n" -" println!(\"{a:?} not_equals {b:?}: {}\", a.not_equal(&b));\n" -"}\n" -"```" -msgstr "" - -#: src/traits/default-methods.md:32 -msgid "" -"Traits may specify pre-implemented (default) methods and methods that users " -"are required to implement themselves. Methods with default implementations " -"can rely on required methods." -msgstr "" -"特徵可能會指定預先實作的 (預設) 方法,以及使用者必須自行實作的方法。採用預設" -"實作項目的方法可以信賴必要方法。" - -#: src/traits/default-methods.md:35 -msgid "Move method `not_equal` to a new trait `NotEqual`." -msgstr "" - -#: src/traits/default-methods.md:37 -msgid "Make `NotEqual` a super trait for `Equal`." -msgstr "" - -#: src/traits/default-methods.md:38 -msgid "" -"```rust,editable,compile_fail\n" -"trait NotEqual: Equals {\n" -" fn not_equal(&self, other: &Self) -> bool {\n" -" !self.equal(other)\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/traits/default-methods.md:46 -msgid "Provide a blanket implementation of `NotEqual` for `Equal`." -msgstr "" - -#: src/traits/default-methods.md:47 -msgid "" -"```rust,editable,compile_fail\n" -"trait NotEqual {\n" -" fn not_equal(&self, other: &Self) -> bool;\n" -"}\n" -"\n" -"impl NotEqual for T where T: Equals {\n" -" fn not_equal(&self, other: &Self) -> bool {\n" -" !self.equal(other)\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/traits/default-methods.md:58 -msgid "" -"With the blanket implementation, you no longer need `NotEqual` as a super " -"trait for `Equal`." -msgstr "" - -#: src/traits/trait-bounds.md:3 +#: src/generics/trait-bounds.md msgid "" "When working with generics, you often want to require the types to implement " "some trait, so that you can call this trait's methods." msgstr "" "使用泛型時,您通常會需要該型別實作 某些特徵,這樣才能呼叫該特徵的方法。" -#: src/traits/trait-bounds.md:6 +#: src/generics/trait-bounds.md msgid "You can do this with `T: Trait` or `impl Trait`:" msgstr "您可以使用 `T: Trait` 或 `impl Trait` 執行此操作:" -#: src/traits/trait-bounds.md:8 -msgid "" -"```rust,editable\n" -"fn duplicate(a: T) -> (T, T) {\n" -" (a.clone(), a.clone())\n" -"}\n" -"\n" -"// Syntactic sugar for:\n" -"// fn add_42_millions>(x: T) -> i32 {\n" -"fn add_42_millions(x: impl Into) -> i32 {\n" -" x.into() + 42_000_000\n" -"}\n" -"\n" -"// struct NotClonable;\n" -"\n" -"fn main() {\n" -" let foo = String::from(\"foo\");\n" -" let pair = duplicate(foo);\n" -" println!(\"{pair:?}\");\n" -"\n" -" let many = add_42_millions(42_i8);\n" -" println!(\"{many}\");\n" -" let many_more = add_42_millions(10_000_000);\n" -" println!(\"{many_more}\");\n" -"}\n" -"```" -msgstr "" +#: src/generics/trait-bounds.md +msgid "// struct NotClonable;\n" +msgstr "// struct NotClonable;\n" -#: src/traits/trait-bounds.md:35 +#: src/generics/trait-bounds.md +msgid "\"{pair:?}\"" +msgstr "\"{pair:?}\"" + +#: src/generics/trait-bounds.md +msgid "Try making a `NonClonable` and passing it to `duplicate`." +msgstr "請嘗試建立 `NonClonable` 並將其傳送至 `duplicate`。" + +#: src/generics/trait-bounds.md +msgid "When multiple traits are necessary, use `+` to join them." +msgstr "如果需要多個特徵,請使用 `+` 彙整特徵。" + +#: src/generics/trait-bounds.md msgid "Show a `where` clause, students will encounter it when reading code." msgstr "顯示 `where` 子句,學生在閱讀程式碼時會看到此內容。" -#: src/traits/trait-bounds.md:37 -msgid "" -"```rust,ignore\n" -"fn duplicate(a: T) -> (T, T)\n" -"where\n" -" T: Clone,\n" -"{\n" -" (a.clone(), a.clone())\n" -"}\n" -"```" -msgstr "" -"```rust,ignore\n" -"fn duplicate(a: T) -> (T, T)\n" -"where\n" -" T: Clone,\n" -"{\n" -" (a.clone(), a.clone())\n" -"}\n" -"```" - -#: src/traits/trait-bounds.md:46 +#: src/generics/trait-bounds.md msgid "It declutters the function signature if you have many parameters." msgstr "如果您有多個參數,這個子句可以整理函式簽名。" -#: src/traits/trait-bounds.md:47 +#: src/generics/trait-bounds.md msgid "It has additional features making it more powerful." msgstr "這個子句具有額外功能,因此效能也更強大。" -#: src/traits/trait-bounds.md:48 +#: src/generics/trait-bounds.md msgid "" "If someone asks, the extra feature is that the type on the left of \":\" can " "be arbitrary, like `Option`." @@ -9806,48 +5975,54 @@ msgstr "" "如果有人提問,請說明額外功能是指 \":\" 左側的類別可為任意值,例如 " "`Option`。" -#: src/traits/impl-trait.md:1 -msgid "`impl Trait`" -msgstr "`impl Trait`" +#: src/generics/trait-bounds.md +msgid "" +"Note that Rust does not (yet) support specialization. For example, given the " +"original `duplicate`, it is invalid to add a specialized `duplicate(a: u32)`." +msgstr "" +"請注意,Rust 尚不支援特化。舉例來說,對於原始的 `duplicate`,您無法新增特化" +"的 `duplicate(a: u32)`。" -#: src/traits/impl-trait.md:3 +#: src/generics/impl-trait.md msgid "" "Similar to trait bounds, an `impl Trait` syntax can be used in function " "arguments and return values:" msgstr "與特徵界限類似,`impl Trait` 語法可用於 函式引數和回傳值中:" -#: src/traits/impl-trait.md:6 +#: src/generics/impl-trait.md msgid "" -"```rust,editable\n" -"use std::fmt::Display;\n" -"\n" -"fn get_x(name: impl Display) -> impl Display {\n" -" format!(\"Hello {name}\")\n" -"}\n" -"\n" -"fn main() {\n" -" let x = get_x(\"foo\");\n" -" println!(\"{x}\");\n" -"}\n" -"```" +"// Syntactic sugar for:\n" +"// fn add_42_millions>(x: T) -> i32 {\n" msgstr "" +"// Syntactic sugar for:\n" +"// fn add_42_millions>(x: T) -> i32 {\n" -#: src/traits/impl-trait.md:19 -msgid "`impl Trait` allows you to work with types which you cannot name." -msgstr "`impl Trait` 可讓您使用無法命名的型別。" +#: src/generics/impl-trait.md +msgid "\"{many}\"" +msgstr "\"{many}\"" -#: src/traits/impl-trait.md:23 +#: src/generics/impl-trait.md +msgid "\"{many_more}\"" +msgstr "\"{many_more}\"" + +#: src/generics/impl-trait.md +msgid "\"debuggable: {debuggable:?}\"" +msgstr "\"debuggable: {debuggable:?}\"" + +#: src/generics/impl-trait.md +#, fuzzy msgid "" -"The meaning of `impl Trait` is a bit different in the different positions." +"`impl Trait` allows you to work with types which you cannot name. The " +"meaning of `impl Trait` is a bit different in the different positions." msgstr "`impl Trait` 的涵義會因使用位置而有些微不同。" -#: src/traits/impl-trait.md:25 +#: src/generics/impl-trait.md msgid "" "For a parameter, `impl Trait` is like an anonymous generic parameter with a " "trait bound." msgstr "對參數來說,`impl Trait` 就像是具有特徵界限的匿名泛型參數。" -#: src/traits/impl-trait.md:27 +#: src/generics/impl-trait.md msgid "" "For a return type, it means that the return type is some concrete type that " "implements the trait, without naming the type. This can be useful when you " @@ -9856,7 +6031,7 @@ msgstr "" "對回傳型別來說,`impl Trait` 代表回傳型別就是實作特徵的 某些具體型別,因而不" "必指名特定型別。如果您不想在公用 API 中公開具體型別, 這就非常有用。" -#: src/traits/impl-trait.md:31 +#: src/generics/impl-trait.md msgid "" "Inference is hard in return position. A function returning `impl Foo` picks " "the concrete type it returns, without writing it out in the source. A " @@ -9870,188 +6045,909 @@ msgstr "" "回傳 符合 `B` 的任何型別 ,而呼叫端可能需要選擇一個型別,例如使用 `let x: " "Vec<_> = foo.collect()` 或 Turbofish:`foo.collect::>()`。" -#: src/traits/impl-trait.md:37 +#: src/generics/impl-trait.md msgid "" -"This example is great, because it uses `impl Display` twice. It helps to " -"explain that nothing here enforces that it is _the same_ `impl Display` " -"type. If we used a single `T: Display`, it would enforce the constraint " -"that input `T` and return `T` type are the same type. It would not work for " -"this particular function, as the type we expect as input is likely not what " -"`format!` returns. If we wanted to do the same via `: Display` syntax, we'd " -"need two independent generic parameters." +"What is the type of `debuggable`? Try `let debuggable: () = ..` to see what " +"the error message shows." msgstr "" -"這個例子非常好,因為 `impl Display` 使用了兩次。這有助於說明此處沒有 任何項目" -"會強制使用「相同的」`impl Display` 型別。如果我們使用單一的 `T: Display`,則" -"會強制限制「輸入」`T` 和「回傳」`T` 屬於同一型別。 但這並不適合這個特定函式," -"因為我們預期做為「輸入」的型別不一定 會是 `format!` 回傳的內容。如要透過 `: " -"Display` 語法執行相同操作,我們會 需要兩個獨立的泛型參數。" +"思考一下,`debuggable` 的型別為何?您可以嘗試使用 `let debuggable: () = ..` " +"查看錯誤訊息顯示的內容。" -#: src/traits/important-traits.md:3 +#: src/generics/exercise.md msgid "" -"We will now look at some of the most common traits of the Rust standard " -"library:" -msgstr "現在來探討 Rust 標準程式庫最常見的幾個特徵:" - -#: src/traits/important-traits.md:5 -msgid "" -"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " -"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " -"used in `for` loops," +"In this short exercise, you will implement a generic `min` function that " +"determines the minimum of two values, using a `LessThan` trait." msgstr "" -"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) 和 " -"[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) " -"用於 `for` 迴圈。" +"在這個簡短練習中,您將使用 `LessThan` 特徵實作泛型 `min` 函式,藉此判定兩個值" +"中的最小值。" -#: src/traits/important-traits.md:6 +#: src/generics/exercise.md src/generics/solution.md +msgid "/// Return true if self is less than other.\n" +msgstr "/// Return true if self is less than other.\n" + +#: src/generics/exercise.md +msgid "// TODO: implement the `min` function used in `main`.\n" +msgstr "// TODO: implement the `min` function used in `main`.\n" + +#: src/generics/exercise.md src/generics/solution.md +msgid "\"Shapiro\"" +msgstr "\"Shapiro\"" + +#: src/generics/exercise.md src/generics/solution.md +msgid "\"Baumann\"" +msgstr "\"Baumann\"" + +#: src/welcome-day-2-afternoon.md +msgid "[Standard Library Types](./std-types.md) (1 hour and 20 minutes)" +msgstr "[標準程式庫型別](./std-types.md) (1 小時 20 分鐘)" + +#: src/welcome-day-2-afternoon.md +msgid "[Standard Library Traits](./std-traits.md) (1 hour and 40 minutes)" +msgstr "[標準程式庫特徵](./std-traits.md) (1 小時 40 分鐘)" + +#: src/welcome-day-2-afternoon.md msgid "" -"[`From`](https://doc.rust-lang.org/std/convert/trait.From.html) and [`Into`]" -"(https://doc.rust-lang.org/std/convert/trait.Into.html) used to convert " -"values," +"Including 10 minute breaks, this session should take about 3 hours and 10 " +"minutes" +msgstr "講解這個主題大約需要 3 小時 10 分鐘" + +#: src/std-types.md +msgid "[Standard Library](./std-types/std.md) (3 minutes)" +msgstr "[標準程式庫](./std-types/std.md) (3 分鐘)" + +#: src/std-types.md +msgid "[Documentation](./std-types/docs.md) (5 minutes)" +msgstr "[說明文件](./std-types/docs.md) (5 分鐘)" + +#: src/std-types.md +msgid "[Option](./std-types/option.md) (10 minutes)" +msgstr "[選項](./std-types/option.md) (10 分鐘)" + +#: src/std-types.md +msgid "[Result](./std-types/result.md) (10 minutes)" +msgstr "[結果](./std-types/result.md) (10 分鐘)" + +#: src/std-types.md +msgid "[String](./std-types/string.md) (10 minutes)" +msgstr "[字串](./std-types/string.md) (10 分鐘)" + +#: src/std-types.md +msgid "[Vec](./std-types/vec.md) (10 minutes)" +msgstr "[Vec](./std-types/vec.md) (10 分鐘)" + +#: src/std-types.md +msgid "[HashMap](./std-types/hashmap.md) (10 minutes)" +msgstr "[HashMap](./std-types/hashmap.md) (10 分鐘)" + +#: src/std-types.md +msgid "[Exercise: Counter](./std-types/exercise.md) (20 minutes)" +msgstr "[練習:計數器](./std-types/exercise.md) (20 分鐘)" + +#: src/std-types.md +msgid "This segment should take about 1 hour and 20 minutes" +msgstr "講解這個主題大約需要 1 小時 20 分鐘" + +#: src/std-types.md +msgid "" +"For each of the slides in this section, spend some time reviewing the " +"documentation pages, highlighting some of the more common methods." msgstr "" -"[`From`](https://doc.rust-lang.org/std/convert/trait.From.html) 和 [`Into`]" -"(https://doc.rust-lang.org/std/convert/trait.Into.html) 用來轉換值。" +"請針對這節的每張投影片,花點時間帶學員詳讀說明文件頁面,並向他們強調一些較常" +"見的方法。" -#: src/traits/important-traits.md:7 +#: src/std-types/std.md +#, fuzzy msgid "" -"[`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and [`Write`]" -"(https://doc.rust-lang.org/std/io/trait.Write.html) used for IO," +"Rust comes with a standard library which helps establish a set of common " +"types used by Rust libraries and programs. This way, two libraries can work " +"together smoothly because they both use the same `String` type." msgstr "" -"[`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) 和 [`Write`]" -"(https://doc.rust-lang.org/std/io/trait.Write.html) 用於 IO。" +"Rust 提供標準函式庫,可用於建立供 Rust 函式庫和程式使用的常用型別集。如此一" +"來,兩個函式庫會使用相同的 `String` 型別,因此能夠順暢搭配運作。" -#: src/traits/important-traits.md:8 +#: src/std-types/std.md +#, fuzzy msgid "" -"[`Add`](https://doc.rust-lang.org/std/ops/trait.Add.html), [`Mul`](https://" -"doc.rust-lang.org/std/ops/trait.Mul.html), ... used for operator " -"overloading, and" +"In fact, Rust contains several layers of the Standard Library: `core`, " +"`alloc` and `std`." +msgstr "Rust 實際上含有多種層級的標準函式庫,分別是 `core`、`alloc` 和 `std`。" + +#: src/std-types/std.md +#, fuzzy +msgid "" +"`core` includes the most basic types and functions that don't depend on " +"`libc`, allocator or even the presence of an operating system." msgstr "" -"[`Add`](https://doc.rust-lang.org/std/ops/trait.Add.html)、[`Mul`](https://" -"doc.rust-lang.org/std/ops/trait.Mul.html) 等用於運算子超載。" +"`core` 包括最基本的型別與函式,這些型別與函式不依附於 `libc`、配置器或作業系" +"統。" -#: src/traits/important-traits.md:9 +#: src/std-types/std.md msgid "" -"[`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) used for " -"defining destructors." +"`alloc` includes types which require a global heap allocator, such as `Vec`, " +"`Box` and `Arc`." +msgstr "`alloc` 包括需要全域堆積配置器的型別,例如 `Vec`、`Box` 和 `Arc`。" + +#: src/std-types/std.md +msgid "" +"Embedded Rust applications often only use `core`, and sometimes `alloc`." +msgstr "嵌入式 Rust 應用程式通常只使用 `core`,偶爾會使用 `alloc`。" + +#: src/std-types/docs.md +msgid "Rust comes with extensive documentation. For example:" +msgstr "Rust 說明文件的主題涵蓋甚廣,包括:" + +#: src/std-types/docs.md +#, fuzzy +msgid "" +"All of the details about [loops](https://doc.rust-lang.org/stable/reference/" +"expressions/loop-expr.html)." msgstr "" -"[`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) 用於定義解構函" -"式。" +"如果你想提早跳出迴圈,可以使用 [`break`]((https://doc.rust-lang.org/" +"reference/expressions/loop-expr.html#break-expressions))," -#: src/traits/important-traits.md:10 +#: src/std-types/docs.md msgid "" -"[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) used " -"to construct a default instance of a type." +"Primitive types like [`u8`](https://doc.rust-lang.org/stable/std/primitive." +"u8.html)." msgstr "" -"[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) 用於建" -"構型別的預設執行個體。" +"基本型別,例如 [`u8`](https://doc.rust-lang.org/stable/std/primitive.u8." +"html)。" -#: src/traits/iterator.md:1 -msgid "Iterators" -msgstr "疊代器" - -#: src/traits/iterator.md:3 +#: src/std-types/docs.md +#, fuzzy msgid "" -"You can implement the [`Iterator`](https://doc.rust-lang.org/std/iter/trait." -"Iterator.html) trait on your own types:" +"Standard library types like [`Option`](https://doc.rust-lang.org/stable/std/" +"option/enum.Option.html) or [`BinaryHeap`](https://doc.rust-lang.org/stable/" +"std/collections/struct.BinaryHeap.html)." msgstr "" -"您可以自行在型別上實作 [`Iterator`](https://doc.rust-lang.org/std/iter/trait." -"Iterator.html) 特徵:" +"[`str`](https://doc.rust-lang.org/std/primitive.str.html) 和 [`String`]" +"(https://doc.rust-lang.org/std/string/struct.String.html)" -#: src/traits/iterator.md:5 +#: src/std-types/docs.md +msgid "In fact, you can document your own code:" +msgstr "您其實可以將程式碼記錄下來:" + +#: src/std-types/docs.md msgid "" -"```rust,editable\n" -"struct Fibonacci {\n" -" curr: u32,\n" -" next: u32,\n" -"}\n" -"\n" -"impl Iterator for Fibonacci {\n" -" type Item = u32;\n" -"\n" -" fn next(&mut self) -> Option {\n" -" let new_next = self.curr + self.next;\n" -" self.curr = self.next;\n" -" self.next = new_next;\n" -" Some(self.curr)\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let fib = Fibonacci { curr: 0, next: 1 };\n" -" for (i, n) in fib.enumerate().take(5) {\n" -" println!(\"fib({i}): {n}\");\n" -" }\n" -"}\n" -"```" +"/// Determine whether the first argument is divisible by the second " +"argument.\n" +"///\n" +"/// If the second argument is zero, the result is false.\n" +msgstr "" +"/// Determine whether the first argument is divisible by the second " +"argument.\n" +"///\n" +"/// If the second argument is zero, the result is false.\n" + +#: src/std-types/docs.md +msgid "" +"The contents are treated as Markdown. All published Rust library crates are " +"automatically documented at [`docs.rs`](https://docs.rs) using the [rustdoc]" +"(https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html) tool. It is " +"idiomatic to document all public items in an API using this pattern." +msgstr "" +"系統會將內容視為 Markdown。所有已發布的 Rust 程式庫 Crate,都會使用 [rustdoc]" +"(https://doc.rust-lang.org/rustdoc/what-is-rustdoc.html) 工具自動記錄於 " +"[`docs.rs`](https://docs.rs) 中。這種記錄 API 中所有公開項目的模式是慣用做" +"法。" + +#: src/std-types/docs.md +msgid "" +"To document an item from inside the item (such as inside a module), use `//!" +"` or `/*! .. */`, called \"inner doc comments\":" +msgstr "" +"如要從項目內部 (例如在模組內) 記錄項目,請使用 `//!` 或 `/*! .. */`,這也稱做" +"「內部文件註解」:" + +#: src/std-types/docs.md +msgid "" +"//! This module contains functionality relating to divisibility of " +"integers.\n" +msgstr "" +"//! This module contains functionality relating to divisibility of " +"integers.\n" + +#: src/std-types/docs.md +#, fuzzy +msgid "" +"Show students the generated docs for the `rand` crate at ." +msgstr "" +"向學生展示針對 `rand` Crate 產生的文件,路徑如下:[`docs.rs/rand`](https://" +"docs.rs/rand)。" + +#: src/std-types/option.md +#, fuzzy +msgid "Option" +msgstr "例外狀況" + +#: src/std-types/option.md +msgid "" +"We have already seen some use of `Option`. It stores either a value of " +"type `T` or nothing. For example, [`String::find`](https://doc.rust-lang.org/" +"stable/std/string/struct.String.html#method.find) returns an `Option`." +msgstr "" +"我們已看過 `Option` 的某些用法,包括儲存型別為 `T` 的值,或不儲存任何東" +"西。舉例來說,[`String::find`](https://doc.rust-lang.org/stable/std/string/" +"struct.String.html#method.find) 會傳回 `Option`。" + +#: src/std-types/option.md +msgid "\"Löwe 老虎 Léopard Gepardi\"" +msgstr "\"Löwe 老虎 Léopard Gepardi\"" + +#: src/std-types/option.md +msgid "'é'" +msgstr "'é'" + +#: src/std-types/option.md +msgid "\"find returned {position:?}\"" +msgstr "\"find returned {position:?}\"" + +#: src/std-types/option.md +msgid "'Z'" +msgstr "'Z'" + +#: src/std-types/option.md +msgid "\"Character not found\"" +msgstr "\"Character not found\"" + +#: src/std-types/option.md +#, fuzzy +msgid "`Option` is widely used, not just in the standard library." +msgstr "`Option` 和 `Result` 這兩種型別的使用範圍很廣,不侷限於標準函式庫。" + +#: src/std-types/option.md +msgid "" +"`unwrap` will return the value in an `Option`, or panic. `expect` is similar " +"but takes an error message." +msgstr "" +"`unwrap` 會在 `Option` 或恐慌中傳回值。`expect` 也類似,但會收到錯誤訊息。" + +#: src/std-types/option.md +msgid "" +"You can panic on None, but you can't \"accidentally\" forget to check for " +"None." +msgstr "您可以讓程式在 None 發生恐慌,但不能「因錯而」忘記檢查 None。" + +#: src/std-types/option.md +msgid "" +"It's common to `unwrap`/`expect` all over the place when hacking something " +"together, but production code typically handles `None` in a nicer fashion." +msgstr "" +"如果是要設計某些臨時程式,通常會在各處 `unwrap`/`expect`,但實際運作的程式碼" +"一般會以較好的方式處理 `None`。" + +#: src/std-types/option.md +msgid "" +"The niche optimization means that `Option` often has the same size in " +"memory as `T`." +msgstr "所謂區位最佳化,代表 `Option` 的記憶體大小通常與 `T` 相同。" + +#: src/std-types/result.md +msgid "Result" +msgstr "結果" + +#: src/std-types/result.md +msgid "" +"`Result` is similar to `Option`, but indicates the success or failure of an " +"operation, each with a different type. This is similar to the `Res` defined " +"in the expression exercise, but generic: `Result` where `T` is used in " +"the `Ok` variant and `E` appears in the `Err` variant." +msgstr "" +"`Result` 和 `Option` 類似,但會指出作業成功或失敗,且各自都有不同的型別。雖然" +"和運算式練習中定義的 `Res` 很像,但這屬於泛型,也就是 `Result`,其中 " +"`T` 用於 `Ok` 變體,而 `E` 則會出現在 `Err` 變數中。" + +#: src/std-types/result.md +msgid "\"diary.txt\"" +msgstr "\"diary.txt\"" + +#: src/std-types/result.md +msgid "\"Dear diary: {contents} ({bytes} bytes)\"" +msgstr "\"Dear diary: {contents} ({bytes} bytes)\"" + +#: src/std-types/result.md +msgid "\"Could not read file content\"" +msgstr "\"Could not read file content\"" + +#: src/std-types/result.md +msgid "\"The diary could not be opened: {err}\"" +msgstr "\"The diary could not be opened: {err}\"" + +#: src/std-types/result.md +msgid "" +"As with `Option`, the successful value sits inside of `Result`, forcing the " +"developer to explicitly extract it. This encourages error checking. In the " +"case where an error should never happen, `unwrap()` or `expect()` can be " +"called, and this is a signal of the developer intent too." +msgstr "" +"就跟使用 `Option` 一樣,成功的值會在 Result 內部,這會強制開發人員明確擷取該" +"值,進而有利於檢查錯誤。在應該絕對不會發生錯誤的情況下,可以呼叫 `unwrap()` " +"或 `expect()`,這也是開發人員意圖的訊號。" + +#: src/std-types/result.md +#, fuzzy +msgid "" +"`Result` documentation is a recommended read. Not during the course, but it " +"is worth mentioning. It contains a lot of convenience methods and functions " +"that help functional-style programming." +msgstr "" +"建議您參閱 `Result` 說明文件。這不涵蓋在課程內,但值得一提。這份文件收錄許多" +"方便的方法和函式,有助於您進行函式程式設計。" + +#: src/std-types/result.md +msgid "" +"`Result` is the standard type to implement error handling as we will see on " +"Day 3." +msgstr "`Result` 是實作錯誤處理的標準型別,我們將在第 3 天的課程中介紹。" + +#: src/std-types/string.md +msgid "String" +msgstr "String" + +#: src/std-types/string.md +msgid "" +"[`String`](https://doc.rust-lang.org/std/string/struct.String.html) is the " +"standard heap-allocated growable UTF-8 string buffer:" +msgstr "" +"[`String`](https://doc.rust-lang.org/std/string/struct.String.html) 是標準堆" +"積配置的可成長 UTF-8 字串緩衝區:" + +#: src/std-types/string.md src/std-traits/read-and-write.md +#: src/memory-management/review.md src/testing/unit-tests.md +#: src/concurrency/scoped-threads.md +msgid "\"Hello\"" +msgstr "\"Hello\"" + +#: src/std-types/string.md +msgid "\"s1: len = {}, capacity = {}\"" +msgstr "\"s1: len = {}, capacity = {}\"" + +#: src/std-types/string.md +msgid "'!'" +msgstr "'!'" + +#: src/std-types/string.md +msgid "\"s2: len = {}, capacity = {}\"" +msgstr "\"s2: len = {}, capacity = {}\"" + +#: src/std-types/string.md +msgid "\"🇨🇭\"" +msgstr "\"🇨🇭\"" + +#: src/std-types/string.md +msgid "\"s3: len = {}, number of chars = {}\"" +msgstr "\"s3: len = {}, number of chars = {}\"" + +#: src/std-types/string.md +msgid "" +"`String` implements [`Deref`](https://doc.rust-lang.org/std/" +"string/struct.String.html#deref-methods-str), which means that you can call " +"all `str` methods on a `String`." +msgstr "" +"`String` 會實作 [`Deref`](https://doc.rust-lang.org/std/string/" +"struct.String.html#deref-methods-str)。也就是說,您可以在 `String` 上呼叫所" +"有 `str` 方法。" + +#: src/std-types/string.md +msgid "" +"`String::new` returns a new empty string, use `String::with_capacity` when " +"you know how much data you want to push to the string." +msgstr "" +"`String::new` 會傳回新的空白字串,如果您知道要向字串推送多少資料,請使用 " +"`String::with_capacity`。" + +#: src/std-types/string.md +msgid "" +"`String::len` returns the size of the `String` in bytes (which can be " +"different from its length in characters)." +msgstr "" +"`String::len` 會傳回 `String` 的大小 (以位元組為單位,可能與以字元為單位的長" +"度不同)。" + +#: src/std-types/string.md +msgid "" +"`String::chars` returns an iterator over the actual characters. Note that a " +"`char` can be different from what a human will consider a \"character\" due " +"to [grapheme clusters](https://docs.rs/unicode-segmentation/latest/" +"unicode_segmentation/struct.Graphemes.html)." +msgstr "" +"`String::chars` 會傳回實際字元的疊代器。請注意,由於[字形叢集](https://docs." +"rs/unicode-segmentation/latest/unicode_segmentation/struct.Graphemes.html)的" +"關係,`char` 和一般人所認為的「字元」可能不同。" + +#: src/std-types/string.md +msgid "" +"When people refer to strings they could either be talking about `&str` or " +"`String`." +msgstr "提到字串時,一般人可能是指 `&str` 或 `String`。" + +#: src/std-types/string.md +msgid "" +"When a type implements `Deref`, the compiler will let you " +"transparently call methods from `T`." +msgstr "" +"當型別實作 `Deref` 時,編譯器可讓您以公開透明的方式呼叫 `T` 中的" +"方法。" + +#: src/std-types/string.md +msgid "" +"We haven't discussed the `Deref` trait yet, so at this point this mostly " +"explains the structure of the sidebar in the documentation." +msgstr "我們尚未討論 `Deref` 特徵,因此目前主要會講解說明文件中的側欄結構。" + +#: src/std-types/string.md +msgid "" +"`String` implements `Deref` which transparently gives it " +"access to `str`'s methods." +msgstr "" +"`String` 會實作 `Deref`,後者能以公開透明的方式授予前者 `str` " +"方法的存取權。" + +#: src/std-types/string.md +#, fuzzy +msgid "Write and compare `let s3 = s1.deref();` and `let s3 = &*s1;`." +msgstr "編寫及比較 `let s3 = s1.deref();` 和 `let s3 = &*s1`;。" + +#: src/std-types/string.md +msgid "" +"`String` is implemented as a wrapper around a vector of bytes, many of the " +"operations you see supported on vectors are also supported on `String`, but " +"with some extra guarantees." +msgstr "" +"`String` 是以包裝函式的形式在位元組向量的四周實作,許多在向量上支援的作業也適" +"用於 `String`,但需要某些額外保證。" + +#: src/std-types/string.md +msgid "Compare the different ways to index a `String`:" +msgstr "請比較各種為 `String` 建立索引的方法:" + +#: src/std-types/string.md +msgid "" +"To a character by using `s3.chars().nth(i).unwrap()` where `i` is in-bound, " +"out-of-bounds." +msgstr "使用 `s3.chars().nth(i).unwrap()` 變為字元,其中 `i` 代表是否出界。" + +#: src/std-types/string.md +msgid "" +"To a substring by using `s3[0..4]`, where that slice is on character " +"boundaries or not." +msgstr "使用 `s3[0..4]` 變為子字串,其中該切片會位於字元邊界上,也可能不會。" + +#: src/std-types/string.md +msgid "" +"Many types can be converted to a string with the [`to_string`](https://doc." +"rust-lang.org/std/string/trait.ToString.html#tymethod.to_string) method. " +"This trait is automatically implemented for all types that implement " +"`Display`, so anything that can be formatted can also be converted to a " +"string." msgstr "" -#: src/traits/iterator.md:32 +#: src/std-types/vec.md msgid "" -"The `Iterator` trait implements many common functional programming " -"operations over collections (e.g. `map`, `filter`, `reduce`, etc). This is " -"the trait where you can find all the documentation about them. In Rust these " -"functions should produce the code as efficient as equivalent imperative " -"implementations." +"[`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) is the standard " +"resizable heap-allocated buffer:" msgstr "" -"`Iterator` 特徵會對集合實作許多常見的函式程式操作,例如 `map`、`filter`、 " -"`reduce` 等等。您可以藉由此特徵找出所有相關的說明文件。在 Rust 中,這些 函式" -"會產生程式碼,且應與對應的命令式實作項目一樣有效率。" +"[`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) 是可調整大小的標準" +"堆積配置緩衝區:" -#: src/traits/iterator.md:37 +#: src/std-types/vec.md +msgid "\"v1: len = {}, capacity = {}\"" +msgstr "\"v1: len = {}, capacity = {}\"" + +#: src/std-types/vec.md +msgid "\"v2: len = {}, capacity = {}\"" +msgstr "\"v2: len = {}, capacity = {}\"" + +#: src/std-types/vec.md +msgid "// Canonical macro to initialize a vector with elements.\n" +msgstr "// Canonical macro to initialize a vector with elements.\n" + +#: src/std-types/vec.md +msgid "// Retain only the even elements.\n" +msgstr "// Retain only the even elements.\n" + +#: src/std-types/vec.md +msgid "\"{v3:?}\"" +msgstr "\"{v3:?}\"" + +#: src/std-types/vec.md +msgid "// Remove consecutive duplicates.\n" +msgstr "// Remove consecutive duplicates.\n" + +#: src/std-types/vec.md msgid "" -"`IntoIterator` is the trait that makes for loops work. It is implemented by " -"collection types such as `Vec` and references to them such as `&Vec` " -"and `&[T]`. Ranges also implement it. This is why you can iterate over a " -"vector with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist." +"`Vec` implements [`Deref`](https://doc.rust-lang.org/std/vec/" +"struct.Vec.html#deref-methods-%5BT%5D), which means that you can call slice " +"methods on a `Vec`." msgstr "" -"`IntoIterator` 是迫使 for 迴圈運作的特徵。此特徵由集合型別(例如 `Vec`) " -"和相關參照 (`&Vec` 與 `&[T]`) 實作而成。此外,範圍也會實作這項特徵。 這就" -"說明了您為何可以透過 `for i in some_vec { .. }` 對向量進行疊代,即使沒有 " -"`some_vec.next()` 也無妨。" +"`Vec` 會實作 [`Deref`](https://doc.rust-lang.org/std/vec/" +"struct.Vec.html#deref-methods-%5BT%5D)。也就是說,您可以在 `Vec` 上呼叫切片方" +"法。" -#: src/traits/from-iterator.md:3 +#: src/std-types/vec.md +#, fuzzy msgid "" -"[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) " -"lets you build a collection from an [`Iterator`](https://doc.rust-lang.org/" -"std/iter/trait.Iterator.html)." +"`Vec` is a type of collection, along with `String` and `HashMap`. The data " +"it contains is stored on the heap. This means the amount of data doesn't " +"need to be known at compile time. It can grow or shrink at runtime." msgstr "" -"[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) " -"可讓您透過 [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator." -"html) 建構集合。" +"`Vec` 是一種集合型別,與 `String` 和 `HashMap` 都一樣。`Vec` 內含的資料會儲存" +"在堆積上。這表示在編譯期間無需得知資料量,可在執行階段増量或減量。" -#: src/traits/from-iterator.md:5 +#: src/std-types/vec.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let primes = vec![2, 3, 5, 7];\n" -" let prime_squares = primes\n" -" .into_iter()\n" -" .map(|prime| prime * prime)\n" -" .collect::>();\n" -"}\n" -"```" +"Notice how `Vec` is a generic type too, but you don't have to specify `T` " +"explicitly. As always with Rust type inference, the `T` was established " +"during the first `push` call." msgstr "" +"請留意 `Vec` 也能做為泛型型別,但您不必明確指定 `T`。和往常的 Rust 型別推" +"論一樣,系統會在第一次 `push` 呼叫期間建立 `T`。" -#: src/traits/from-iterator.md:17 +#: src/std-types/vec.md msgid "" -"`Iterator` implements `fn collect(self) -> B where B: FromIterator, Self: Sized`" +"`vec![...]` is a canonical macro to use instead of `Vec::new()` and it " +"supports adding initial elements to the vector." msgstr "" -"`Iterator` implements `fn collect(self) -> B where B: FromIterator, Self: Sized`" +"`vec![...]` 是用於取代 `Vec::new()` 的標準巨集,且支援在向量中加入初始元素。" -#: src/traits/from-iterator.md:23 +#: src/std-types/vec.md msgid "" -"There are also implementations which let you do cool things like convert an " -"`Iterator>` into a `Result, E>`." +"To index the vector you use `[` `]`, but they will panic if out of bounds. " +"Alternatively, using `get` will return an `Option`. The `pop` function will " +"remove the last element." msgstr "" -"您也可以利用部分實作項目完成某些酷炫操作,例如將 `Iterator>` 轉換成 `Result, E>`。" +"如要為向量建立索引,請使用 `[` `]`,但如果超出範圍會引發恐慌。或者,使用 " +"`get` 則可傳回 `Option`。`pop` 函式會移除最後一個元素。" -#: src/traits/from-into.md:1 -msgid "`From` and `Into`" -msgstr "`From` 和 `Into`" +#: src/std-types/vec.md +msgid "" +"Slices are covered on day 3. For now, students only need to know that a " +"value of type `Vec` gives access to all of the documented slice methods, too." +msgstr "" +"我們會在第 3 天談到切片。現階段,學生只需知道 `Vec` 型別的值也能存取所有記錄" +"下來的切片方法。" -#: src/traits/from-into.md:3 +#: src/std-types/hashmap.md +msgid "Standard hash map with protection against HashDoS attacks:" +msgstr "標準雜湊映射,可防範 HashDoS 攻擊:" + +#: src/std-types/hashmap.md +msgid "\"Adventures of Huckleberry Finn\"" +msgstr "\"Adventures of Huckleberry Finn\"" + +#: src/std-types/hashmap.md +msgid "\"Grimms' Fairy Tales\"" +msgstr "\"Grimms' Fairy Tales\"" + +#: src/std-types/hashmap.md +msgid "\"Pride and Prejudice\"" +msgstr "\"Pride and Prejudice\"" + +#: src/std-types/hashmap.md +msgid "\"Les Misérables\"" +msgstr "\"Les Misérables\"" + +#: src/std-types/hashmap.md +msgid "\"We know about {} books, but not Les Misérables.\"" +msgstr "\"We know about {} books, but not Les Misérables.\"" + +#: src/std-types/hashmap.md +msgid "\"Alice's Adventure in Wonderland\"" +msgstr "\"Alice's Adventure in Wonderland\"" + +#: src/std-types/hashmap.md +msgid "\"{book}: {count} pages\"" +msgstr "\"{book}: {count} pages\"" + +#: src/std-types/hashmap.md +msgid "\"{book} is unknown.\"" +msgstr "\"{book} is unknown.\"" + +#: src/std-types/hashmap.md +msgid "// Use the .entry() method to insert a value if nothing is found.\n" +msgstr "// Use the .entry() method to insert a value if nothing is found.\n" + +#: src/std-types/hashmap.md +msgid "\"{page_counts:#?}\"" +msgstr "\"{page_counts:#?}\"" + +#: src/std-types/hashmap.md +msgid "" +"`HashMap` is not defined in the prelude and needs to be brought into scope." +msgstr "我們一開始並未定義 `HashMap`,因此現在需要將其納入課程範圍。" + +#: src/std-types/hashmap.md +msgid "" +"Try the following lines of code. The first line will see if a book is in the " +"hashmap and if not return an alternative value. The second line will insert " +"the alternative value in the hashmap if the book is not found." +msgstr "" +"請嘗試使用以下幾行程式碼。第一行會查看書籍是否在雜湊表中,如果不在,系統會傳" +"回替代值。如果系統找不到書籍,第二行會在雜湊表中插入替代值。" + +#: src/std-types/hashmap.md +msgid "\"Harry Potter and the Sorcerer's Stone\"" +msgstr "\"Harry Potter and the Sorcerer's Stone\"" + +#: src/std-types/hashmap.md +msgid "\"The Hunger Games\"" +msgstr "\"The Hunger Games\"" + +#: src/std-types/hashmap.md +msgid "Unlike `vec!`, there is unfortunately no standard `hashmap!` macro." +msgstr "可惜的是,並沒有所謂標準的 `hashmap!` 巨集。這點與 `vec!` 不同。" + +#: src/std-types/hashmap.md +msgid "" +"Although, since Rust 1.56, HashMap implements [`From<[(K, V); N]>`](https://" +"doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#impl-" +"From%3C%5B(K,+V);+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E), which allows " +"us to easily initialize a hash map from a literal array:" +msgstr "" +"不過,自 Rust 1.56 起,HashMap 會實作 [`From<[(K, V); N]>`](https://doc.rust-" +"lang.org/std/collections/hash_map/struct.HashMap.html#impl-From%3C%5B(K,+V);" +"+N%5D%3E-for-HashMap%3CK,+V,+RandomState%3E),以便讓我們能從常值陣列初始化雜" +"湊映射:" + +#: src/std-types/hashmap.md +msgid "" +"Alternatively HashMap can be built from any `Iterator` which yields key-" +"value tuples." +msgstr "或者,您也可以透過任何能產生鍵/值元組的 `Iterator` 建立 HashMap。" + +#: src/std-types/hashmap.md +msgid "" +"We are showing `HashMap`, and avoid using `&str` as key to make " +"examples easier. Using references in collections can, of course, be done, " +"but it can lead into complications with the borrow checker." +msgstr "" +"我們示範的是 `HashMap`,請避免使用 `&str 做為鍵,讓範例變得更簡" +"單。當然,也可以在集合中使用參照,但這可能會使借用檢查器變得複雜。" + +#: src/std-types/hashmap.md +msgid "" +"Try removing `to_string()` from the example above and see if it still " +"compiles. Where do you think we might run into issues?" +msgstr "" +"請嘗試從上述範例中移除 `to_string()`,看看是否仍可編譯。您認為我們可能會在哪" +"裡遇到問題?" + +#: src/std-types/hashmap.md +msgid "" +"This type has several \"method-specific\" return types, such as `std::" +"collections::hash_map::Keys`. These types often appear in searches of the " +"Rust docs. Show students the docs for this type, and the helpful link back " +"to the `keys` method." +msgstr "" +"這個型別有多個「方法專屬」的傳回型別,例如 `std::collections::hash_map::" +"Keys`。這些型別經常會在 Rust 文件的搜尋結果中出現。請向學生展示這個型別的文" +"件,以及可返回 `keys` 方法的實用連結。" + +#: src/std-types/exercise.md +msgid "" +"In this exercise you will take a very simple data structure and make it " +"generic. It uses a [`std::collections::HashMap`](https://doc.rust-lang.org/" +"stable/std/collections/struct.HashMap.html) to keep track of which values " +"have been seen and how many times each one has appeared." +msgstr "" +"在本練習中,您要使用非常簡單的資料結構並將其設為泛型。此結構會使用 [`std::" +"collections::HashMap`](https://doc.rust-lang.org/stable/std/collections/" +"struct.HashMap.html) 追蹤出現過的值和出現次數。" + +#: src/std-types/exercise.md +msgid "" +"The initial version of `Counter` is hard coded to only work for `u32` " +"values. Make the struct and its methods generic over the type of value being " +"tracked, that way `Counter` can track any type of value." +msgstr "" +"`Counter` 的初始版本經過硬式編碼,僅適用於 `u32` 值。請設法讓結構體和相應的方" +"法成為泛型,而非所追蹤值的型別,這樣 `Counter` 就可以追蹤任何型別的值。" + +#: src/std-types/exercise.md +msgid "" +"If you finish early, try using the [`entry`](https://doc.rust-lang.org/" +"stable/std/collections/struct.HashMap.html#method.entry) method to halve the " +"number of hash lookups required to implement the `count` method." +msgstr "" +"如果您提前完成操作,不妨試著使用 [`entry`](https://doc.rust-lang.org/stable/" +"std/collections/struct.HashMap.html#method.entry) 方法將實作 `count` 方法所需" +"的雜湊查詢數量減半。" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "" +"/// Counter counts the number of times each value of type T has been seen.\n" +msgstr "" +"/// Counter counts the number of times each value of type T has been seen.\n" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "/// Create a new Counter.\n" +msgstr "/// Create a new Counter.\n" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "/// Count an occurrence of the given value.\n" +msgstr "/// Count an occurrence of the given value.\n" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "/// Return the number of times the given value has been seen.\n" +msgstr "/// Return the number of times the given value has been seen.\n" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "\"saw {} values equal to {}\"" +msgstr "\"saw {} values equal to {}\"" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "\"apple\"" +msgstr "\"apple\"" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "\"orange\"" +msgstr "\"orange\"" + +#: src/std-types/exercise.md src/std-types/solution.md +msgid "\"got {} apples\"" +msgstr "\"got {} apples\"" + +#: src/std-traits.md +msgid "[Comparisons](./std-traits/comparisons.md) (10 minutes)" +msgstr "[比較](./std-traits/comparisons.md) (10 分鐘)" + +#: src/std-traits.md +msgid "[Operators](./std-traits/operators.md) (10 minutes)" +msgstr "[運算子](./std-traits/operators.md) (10 分鐘)" + +#: src/std-traits.md +msgid "[From and Into](./std-traits/from-and-into.md) (10 minutes)" +msgstr "[From 和 Into](./std-traits/from-and-into.md) (10 分鐘)" + +#: src/std-traits.md +msgid "[Casting](./std-traits/casting.md) (5 minutes)" +msgstr "[轉換](./std-traits/casting.md) (5 分鐘)" + +#: src/std-traits.md +msgid "[Read and Write](./std-traits/read-and-write.md) (10 minutes)" +msgstr "[Read 和 Write](./std-traits/read-and-write.md) (10 分鐘)" + +#: src/std-traits.md +msgid "[Default, struct update syntax](./std-traits/default.md) (5 minutes)" +msgstr "[Default (結構體更新語法)](./std-traits/default.md) (5 分鐘)" + +#: src/std-traits.md +msgid "[Closures](./std-traits/closures.md) (20 minutes)" +msgstr "[閉包](./std-traits/closures.md) (20 分鐘)" + +#: src/std-traits.md +msgid "[Exercise: ROT13](./std-traits/exercise.md) (30 minutes)" +msgstr "[練習:ROT13](./std-traits/exercise.md) (30 分鐘)" + +#: src/std-traits.md +msgid "This segment should take about 1 hour and 40 minutes" +msgstr "講解這個主題大約需要 1 小時 40 分鐘" + +#: src/std-traits.md +msgid "" +"As with the standard-library types, spend time reviewing the documentation " +"for each trait." +msgstr "和標準程式庫型別一樣,請花時間詳閱每種特徵的說明文件。" + +#: src/std-traits.md +msgid "This section is long. Take a break midway through." +msgstr "這節課時間很長,在中間休息片刻吧。" + +#: src/std-traits/comparisons.md +msgid "" +"These traits support comparisons between values. All traits can be derived " +"for types containing fields that implement these traits." +msgstr "" +"以下特徵可用於比較不同的值。如果欄位會實作這些特徵,您可以針對含有這類欄位的" +"型別衍生所有特徵。" + +#: src/std-traits/comparisons.md +msgid "`PartialEq` and `Eq`" +msgstr "`PartialEq` 和 `Eq`" + +#: src/std-traits/comparisons.md +msgid "" +"`PartialEq` is a partial equivalence relation, with required method `eq` and " +"provided method `ne`. The `==` and `!=` operators will call these methods." +msgstr "" +"`PartialEq` 代表部分對等關係,具有必要方法 `eq` 和提供的方法 `ne`。`==` 和 `!" +"=` 運算子會呼叫這些方法。" + +#: src/std-traits/comparisons.md +msgid "" +"`Eq` is a full equivalence relation (reflexive, symmetric, and transitive) " +"and implies `PartialEq`. Functions that require full equivalence will use " +"`Eq` as a trait bound." +msgstr "" +"`Eq` 代表完整對等關係 (自反、對稱和傳遞性),並且隱含 `PartialEq`。需要完整對" +"等關係的函式會使用 `Eq` 做為特徵界線。" + +#: src/std-traits/comparisons.md +msgid "`PartialOrd` and `Ord`" +msgstr "`PartialOrd` 和 `Ord`" + +#: src/std-traits/comparisons.md +msgid "" +"`PartialOrd` defines a partial ordering, with a `partial_cmp` method. It is " +"used to implement the `<`, `<=`, `>=`, and `>` operators." +msgstr "" +"`PartialOrd` 會透過 `partial_cmp` 方法定義偏序,可用於實作 `<`、`<=`、`>=` " +"和 `>` 運算子。" + +#: src/std-traits/comparisons.md +msgid "`Ord` is a total ordering, with `cmp` returning `Ordering`." +msgstr "`Ord` 是全序,其中 `cmp` 會傳回 `Ordering`。" + +#: src/std-traits/comparisons.md +msgid "" +"`PartialEq` can be implemented between different types, but `Eq` cannot, " +"because it is reflexive:" +msgstr "`PartialEq` 可以在不同的型別之間實作,但具有自反性的 `Eq` 無法:" + +#: src/std-traits/comparisons.md +msgid "" +"In practice, it's common to derive these traits, but uncommon to implement " +"them." +msgstr "實務上一般會衍生這些特徵,但鮮少會實作這些特徵。" + +#: src/std-traits/operators.md +msgid "" +"Operator overloading is implemented via traits in [`std::ops`](https://doc." +"rust-lang.org/std/ops/index.html):" +msgstr "" +"運算子超載會透過 [`std::ops`](https://doc.rust-lang.org/std/ops/index.html): " +"內的特徵實作:" + +#: src/std-traits/operators.md +msgid "\"{:?} + {:?} = {:?}\"" +msgstr "\"{:?} + {:?} = {:?}\"" + +#: src/std-traits/operators.md src/memory-management/drop.md +msgid "Discussion points:" +msgstr "討論要點:" + +#: src/std-traits/operators.md +#, fuzzy +msgid "" +"You could implement `Add` for `&Point`. In which situations is that useful?" +msgstr "您可以針對 `&Point` 實作 `Add`。但這能在哪些情況派上用場?" + +#: src/std-traits/operators.md +msgid "" +"Answer: `Add:add` consumes `self`. If type `T` for which you are overloading " +"the operator is not `Copy`, you should consider overloading the operator for " +"`&T` as well. This avoids unnecessary cloning on the call site." +msgstr "" +"回答:`Add:add` 會耗用 `self`。如果您要超載運算子的型別 `T` 不是 " +"`Copy`,建議您一併為 `&T` 超載運算子。這可避免呼叫點中出現不必要 的複" +"製作業。" + +#: src/std-traits/operators.md +msgid "" +"Why is `Output` an associated type? Could it be made a type parameter of the " +"method?" +msgstr "為什麼 `Output` 是關聯型別?可將其用做方法的型別參數嗎?" + +#: src/std-traits/operators.md +#, fuzzy +msgid "" +"Short answer: Function type parameters are controlled by the caller, but " +"associated types (like `Output`) are controlled by the implementer of a " +"trait." +msgstr "" +"簡答:函式型別參數是由呼叫端控管,但 `Output` 這類關聯型別則由特徵 實" +"作者控管。" + +#: src/std-traits/operators.md +msgid "" +"You could implement `Add` for two different types, e.g. `impl Add<(i32, " +"i32)> for Point` would add a tuple to a `Point`." +msgstr "" +"您可以針對兩種不同型別實作 `Add`,舉例來說, `impl Add<(i32, i32)> for " +"Point` 會將元組新增至 `Point`。" + +#: src/std-traits/from-and-into.md msgid "" "Types implement [`From`](https://doc.rust-lang.org/std/convert/trait.From." "html) and [`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) to " @@ -10061,20 +6957,11 @@ msgstr "" "和 [`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) 以利型別轉" "換作業執行:" -#: src/traits/from-into.md:5 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s = String::from(\"hello\");\n" -" let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]);\n" -" let one = i16::from(true);\n" -" let bigger = i32::from(123i16);\n" -" println!(\"{s}, {addr}, {one}, {bigger}\");\n" -"}\n" -"```" -msgstr "" +#: src/std-traits/from-and-into.md +msgid "\"{s}, {addr}, {one}, {bigger}\"" +msgstr "\"{s}, {addr}, {one}, {bigger}\"" -#: src/traits/from-into.md:15 +#: src/std-traits/from-and-into.md msgid "" "[`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) is " "automatically implemented when [`From`](https://doc.rust-lang.org/std/" @@ -10084,26 +6971,13 @@ msgstr "" "[`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) 也會自動實" "作:" -#: src/traits/from-into.md:17 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let s: String = \"hello\".into();\n" -" let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into();\n" -" let one: i16 = true.into();\n" -" let bigger: i32 = 123i16.into();\n" -" println!(\"{s}, {addr}, {one}, {bigger}\");\n" -"}\n" -"```" -msgstr "" - -#: src/traits/from-into.md:29 +#: src/std-traits/from-and-into.md msgid "" "That's why it is common to only implement `From`, as your type will get " "`Into` implementation too." msgstr "這就是為什麼通常只需實作 `From`,因為型別也會實作 `Into`。" -#: src/traits/from-into.md:30 +#: src/std-traits/from-and-into.md msgid "" "When declaring a function argument input type like \"anything that can be " "converted into a `String`\", the rule is opposite, you should use `Into`. " @@ -10114,11 +6988,78 @@ msgstr "" "反,此時請使用 `Into`。 您的函式會接受實作 `From` 的型別,以及「僅」實作 " "`Into` 的型別。" -#: src/traits/read-write.md:1 -msgid "`Read` and `Write`" -msgstr "`Read` 和 `Write`" +#: src/std-traits/casting.md +msgid "" +"Rust has no _implicit_ type conversions, but does support explicit casts " +"with `as`. These generally follow C semantics where those are defined." +msgstr "" +"Rust 沒有「隱含」型別的轉換,但支援使用 `as` 明確轉換。後者通常會遵循定義前者" +"時所用的 C 語意。" -#: src/traits/read-write.md:3 +#: src/std-traits/casting.md +msgid "\"as u16: {}\"" +msgstr "\"as u16: {}\"" + +#: src/std-traits/casting.md +msgid "\"as i16: {}\"" +msgstr "\"as i16: {}\"" + +#: src/std-traits/casting.md +msgid "\"as u8: {}\"" +msgstr "\"as u8: {}\"" + +#: src/std-traits/casting.md +msgid "" +"The results of `as` are _always_ defined in Rust and consistent across " +"platforms. This might not match your intuition for changing sign or casting " +"to a smaller type -- check the docs, and comment for clarity." +msgstr "" +"在 Rust 中,`as` 的結果「一律」會經過定義,且在不同平台間保持一致。這可能不符" +"合您變更符號或轉換到較小型別時的直觀做法,請檢查文件並加註說明內容。" + +#: src/std-traits/casting.md +msgid "" +"Casting with `as` is a relatively sharp tool that is easy to use " +"incorrectly, and can be a source of subtle bugs as future maintenance work " +"changes the types that are used or the ranges of values in types. Casts are " +"best used only when the intent is to indicate unconditional truncation (e.g. " +"selecting the bottom 32 bits of a `u64` with `as u32`, regardless of what " +"was in the high bits)." +msgstr "" +"雖然使用 `as` 進行型別相當簡單,但是非常容易出錯;舉例來說,如果往後的維護作" +"業改變了所用型別或型別中值的範圍,這常常就是某些細微錯誤的來源。只有在意圖用" +"於指明無條件截斷時,我們才建議使用型別轉換。舉例來說,如果無論高位元中的內容" +"為何,您都只需要 `u64` 的底部 32 位元,就可以使用 `as u32`。" + +#: src/std-traits/casting.md +msgid "" +"For infallible casts (e.g. `u32` to `u64`), prefer using `From` or `Into` " +"over `as` to confirm that the cast is in fact infallible. For fallible " +"casts, `TryFrom` and `TryInto` are available when you want to handle casts " +"that fit differently from those that don't." +msgstr "" +"如果是 `u32` 到 `u64` 這類絕對無誤的型別轉換,適合先使用 `From` 或 `Into` (而" +"非 `as`) 確認轉換確實無誤。對於容易出錯的轉換,如果您想以不同的方式處理,可以" +"使用 `TryFrom` 和 `TryInto`。" + +#: src/std-traits/casting.md +msgid "Consider taking a break after this slide." +msgstr "建議在講解完這張投影片後休息片刻。" + +#: src/std-traits/casting.md +msgid "" +"`as` is similar to a C++ static cast. Use of `as` in cases where data might " +"be lost is generally discouraged, or at least deserves an explanatory " +"comment." +msgstr "" +"`as` 類似於 C++ 的靜態轉換。一般不建議在資料可能遺失的情況下使用 `as`,如果要" +"用,也至少要提供說明註解。" + +#: src/std-traits/casting.md +msgid "This is common in casting integers to `usize` for use as an index." +msgstr "這在將整數轉換為 `usize` 以用做索引時很常見。" + +#: src/std-traits/read-and-write.md msgid "" "Using [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and " "[`BufRead`](https://doc.rust-lang.org/std/io/trait.BufRead.html), you can " @@ -10128,28 +7069,19 @@ msgstr "" "[`BufRead`](https://doc.rust-lang.org/std/io/trait.BufRead.html) 即可對 `u8` " "來源進行抽象化處理:" -#: src/traits/read-write.md:5 -msgid "" -"```rust,editable\n" -"use std::io::{BufRead, BufReader, Read, Result};\n" -"\n" -"fn count_lines(reader: R) -> usize {\n" -" let buf_reader = BufReader::new(reader);\n" -" buf_reader.lines().count()\n" -"}\n" -"\n" -"fn main() -> Result<()> {\n" -" let slice: &[u8] = b\"foo\\nbar\\nbaz\\n\";\n" -" println!(\"lines in slice: {}\", count_lines(slice));\n" -"\n" -" let file = std::fs::File::open(std::env::current_exe()?)?;\n" -" println!(\"lines in file: {}\", count_lines(file));\n" -" Ok(())\n" -"}\n" -"```" -msgstr "" +#: src/std-traits/read-and-write.md +msgid "b\"foo\\nbar\\nbaz\\n\"" +msgstr "b\"foo\\nbar\\nbaz\\n\"" -#: src/traits/read-write.md:23 +#: src/std-traits/read-and-write.md +msgid "\"lines in slice: {}\"" +msgstr "\"lines in slice: {}\"" + +#: src/std-traits/read-and-write.md +msgid "\"lines in file: {}\"" +msgstr "\"lines in file: {}\"" + +#: src/std-traits/read-and-write.md msgid "" "Similarly, [`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) lets " "you abstract over `u8` sinks:" @@ -10157,93 +7089,23 @@ msgstr "" "同樣地,[`Write`](https://doc.rust-lang.org/std/io/trait.Write.html) 則可讓您" "將 `u8` 接收器抽象化:" -#: src/traits/read-write.md:25 -msgid "" -"```rust,editable\n" -"use std::io::{Result, Write};\n" -"\n" -"fn log(writer: &mut W, msg: &str) -> Result<()> {\n" -" writer.write_all(msg.as_bytes())?;\n" -" writer.write_all(\"\\n\".as_bytes())\n" -"}\n" -"\n" -"fn main() -> Result<()> {\n" -" let mut buffer = Vec::new();\n" -" log(&mut buffer, \"Hello\")?;\n" -" log(&mut buffer, \"World\")?;\n" -" println!(\"Logged: {:?}\", buffer);\n" -" Ok(())\n" -"}\n" -"```" -msgstr "" +#: src/std-traits/read-and-write.md +msgid "\"\\n\"" +msgstr "\"\\n\"" -#: src/traits/drop.md:1 -msgid "The `Drop` Trait" -msgstr "`Drop` 特徵" +#: src/std-traits/read-and-write.md src/slices-and-lifetimes/str.md +msgid "\"World\"" +msgstr "\"World\"" -#: src/traits/drop.md:3 -msgid "" -"Values which implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop." -"html) can specify code to run when they go out of scope:" -msgstr "" -"如果值實作了 [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html),即" -"可在超出範圍時指定要執行哪個程式碼:" +#: src/std-traits/read-and-write.md +msgid "\"Logged: {:?}\"" +msgstr "\"Logged: {:?}\"" -#: src/traits/drop.md:5 -msgid "" -"```rust,editable\n" -"struct Droppable {\n" -" name: &'static str,\n" -"}\n" -"\n" -"impl Drop for Droppable {\n" -" fn drop(&mut self) {\n" -" println!(\"Dropping {}\", self.name);\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let a = Droppable { name: \"a\" };\n" -" {\n" -" let b = Droppable { name: \"b\" };\n" -" {\n" -" let c = Droppable { name: \"c\" };\n" -" let d = Droppable { name: \"d\" };\n" -" println!(\"Exiting block B\");\n" -" }\n" -" println!(\"Exiting block A\");\n" -" }\n" -" drop(a);\n" -" println!(\"Exiting main\");\n" -"}\n" -"```" -msgstr "" - -#: src/traits/drop.md:34 src/traits/operators.md:26 -msgid "Discussion points:" -msgstr "討論要點:" - -#: src/traits/drop.md:36 -msgid "Why doesn't `Drop::drop` take `self`?" -msgstr "為什麼 `Drop::drop` 不使用 `self`?" - -#: src/traits/drop.md:37 -msgid "" -"Short-answer: If it did, `std::mem::drop` would be called at the end of the " -"block, resulting in another call to `Drop::drop`, and a stack overflow!" -msgstr "" -"簡答:如果這樣的話,系統會在 區塊結尾呼叫 `std::mem::drop`,進而觸發另一個對 " -"`Drop::drop` 的呼叫並造成堆疊 溢位!" - -#: src/traits/drop.md:40 -msgid "Try replacing `drop(a)` with `a.drop()`." -msgstr "請嘗試將 `drop(a)` 替換為 `a.drop()`。" - -#: src/traits/default.md:1 +#: src/std-traits/default.md msgid "The `Default` Trait" msgstr "`Default` 特徵" -#: src/traits/default.md:3 +#: src/std-traits/default.md msgid "" "[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) trait " "produces a default value for a type." @@ -10251,152 +7113,75 @@ msgstr "" "[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) 特徵會" "產生型別的預設值。" -#: src/traits/default.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug, Default)]\n" -"struct Derived {\n" -" x: u32,\n" -" y: String,\n" -" z: Implemented,\n" -"}\n" -"\n" -"#[derive(Debug)]\n" -"struct Implemented(String);\n" -"\n" -"impl Default for Implemented {\n" -" fn default() -> Self {\n" -" Self(\"John Smith\".into())\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let default_struct: Derived = Default::default();\n" -" println!(\"{default_struct:#?}\");\n" -"\n" -" let almost_default_struct = Derived {\n" -" y: \"Y is set!\".into(),\n" -" ..Default::default()\n" -" };\n" -" println!(\"{almost_default_struct:#?}\");\n" -"\n" -" let nothing: Option = None;\n" -" println!(\"{:#?}\", nothing.unwrap_or_default());\n" -"}\n" -"\n" -"```" -msgstr "" +#: src/std-traits/default.md +msgid "\"John Smith\"" +msgstr "\"John Smith\"" -#: src/traits/default.md:40 +#: src/std-traits/default.md +msgid "\"{default_struct:#?}\"" +msgstr "\"{default_struct:#?}\"" + +#: src/std-traits/default.md +msgid "\"Y is set!\"" +msgstr "\"Y is set!\"" + +#: src/std-traits/default.md +msgid "\"{almost_default_struct:#?}\"" +msgstr "\"{almost_default_struct:#?}\"" + +#: src/std-traits/default.md src/slices-and-lifetimes/exercise.md +#: src/slices-and-lifetimes/solution.md +msgid "\"{:#?}\"" +msgstr "\"{:#?}\"" + +#: src/std-traits/default.md msgid "" "It can be implemented directly or it can be derived via `#[derive(Default)]`." msgstr "這可以直接實作,也可以透過 `#[derive(Default)]` 衍生得出。" -#: src/traits/default.md:41 +#: src/std-traits/default.md +#, fuzzy msgid "" -"Derived implementation will produce an instance where all fields are set to " +"A derived implementation will produce a value where all fields are set to " "their default values." msgstr "衍生的實作項目會產生一個執行個體,其中欄位全都設為預設值。" -#: src/traits/default.md:42 +#: src/std-traits/default.md msgid "This means all types in the struct must implement `Default` too." msgstr "也就是說,該結構體中的所有型別也都必須實作 `Default`。" -#: src/traits/default.md:43 +#: src/std-traits/default.md msgid "" "Standard Rust types often implement `Default` with reasonable values (e.g. " "`0`, `\"\"`, etc)." msgstr "" "標準的 Rust 型別通常會以合理的值 (例如 `0`、`\"\"` 等等) 實作 `Default`。" -#: src/traits/default.md:44 -msgid "The partial struct copy works nicely with default." +#: src/std-traits/default.md +#, fuzzy +msgid "The partial struct initialization works nicely with default." msgstr "部分結構體副本可與預設值完美搭配運作。" -#: src/traits/default.md:45 +#: src/std-traits/default.md +#, fuzzy msgid "" -"Rust standard library is aware that types can implement `Default` and " +"The Rust standard library is aware that types can implement `Default` and " "provides convenience methods that use it." msgstr "" "Rust 標準程式庫瞭解型別可能會實作 `Default`,因此提供了便利的使用方式。" -#: src/traits/operators.md:1 -msgid "`Add`, `Mul`, ..." -msgstr "`Add`、`Mul`..." - -#: src/traits/operators.md:3 +#: src/std-traits/default.md +#, fuzzy msgid "" -"Operator overloading is implemented via traits in [`std::ops`](https://doc." -"rust-lang.org/std/ops/index.html):" +"The `..` syntax is called [struct update syntax](https://doc.rust-lang.org/" +"book/ch05-01-defining-structs.html#creating-instances-from-other-instances-" +"with-struct-update-syntax)." msgstr "" -"運算子超載會透過 [`std::ops`](https://doc.rust-lang.org/std/ops/index.html): " -"內的特徵實作:" +"`..` 語法稱為[結構體更新語法](https://doc.rust-lang.org/book/ch05-01-" +"defining-structs.html#creating-instances-from-other-instances-with-struct-" +"update-syntax)。" -#: src/traits/operators.md:5 -msgid "" -"```rust,editable\n" -"#[derive(Debug, Copy, Clone)]\n" -"struct Point { x: i32, y: i32 }\n" -"\n" -"impl std::ops::Add for Point {\n" -" type Output = Self;\n" -"\n" -" fn add(self, other: Self) -> Self {\n" -" Self {x: self.x + other.x, y: self.y + other.y}\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let p1 = Point { x: 10, y: 20 };\n" -" let p2 = Point { x: 100, y: 200 };\n" -" println!(\"{:?} + {:?} = {:?}\", p1, p2, p1 + p2);\n" -"}\n" -"```" -msgstr "" - -#: src/traits/operators.md:28 -msgid "" -"You could implement `Add` for `&Point`. In which situations is that useful? " -msgstr "您可以針對 `&Point` 實作 `Add`。但這能在哪些情況派上用場?" - -#: src/traits/operators.md:29 -msgid "" -"Answer: `Add:add` consumes `self`. If type `T` for which you are overloading " -"the operator is not `Copy`, you should consider overloading the operator for " -"`&T` as well. This avoids unnecessary cloning on the call site." -msgstr "" -"回答:`Add:add` 會耗用 `self`。如果您要超載運算子的型別 `T` 不是 " -"`Copy`,建議您一併為 `&T` 超載運算子。這可避免呼叫點中出現不必要 的複" -"製作業。" - -#: src/traits/operators.md:33 -msgid "" -"Why is `Output` an associated type? Could it be made a type parameter of the " -"method?" -msgstr "為什麼 `Output` 是關聯型別?可將其用做方法的型別參數嗎?" - -#: src/traits/operators.md:34 -msgid "" -"Short answer: Function type parameters are controlled by the caller, but " -"associated types (like `Output`) are controlled by the implementor of a " -"trait." -msgstr "" -"簡答:函式型別參數是由呼叫端控管,但 `Output` 這類關聯型別則由特徵 實" -"作者控管。" - -#: src/traits/operators.md:37 -msgid "" -"You could implement `Add` for two different types, e.g. `impl Add<(i32, " -"i32)> for Point` would add a tuple to a `Point`." -msgstr "" -"您可以針對兩種不同型別實作 `Add`,舉例來說, `impl Add<(i32, i32)> for " -"Point` 會將元組新增至 `Point`。" - -#: src/traits/closures.md:1 -msgid "Closures" -msgstr "閉包" - -#: src/traits/closures.md:3 +#: src/std-traits/closures.md msgid "" "Closures or lambda expressions have types which cannot be named. However, " "they implement special [`Fn`](https://doc.rust-lang.org/std/ops/trait.Fn." @@ -10408,43 +7193,49 @@ msgstr "" "(https://doc.rust-lang.org/std/ops/trait.FnMut.html) 和 [`FnOnce`](https://" "doc.rust-lang.org/std/ops/trait.FnOnce.html) 特徵:" -#: src/traits/closures.md:8 -msgid "" -"```rust,editable\n" -"fn apply_with_log(func: impl FnOnce(i32) -> i32, input: i32) -> i32 {\n" -" println!(\"Calling function on {input}\");\n" -" func(input)\n" -"}\n" -"\n" -"fn main() {\n" -" let add_3 = |x| x + 3;\n" -" let mul_5 = |x| x * 5;\n" -"\n" -" println!(\"add_3: {}\", apply_with_log(add_3, 10));\n" -" println!(\"mul_5: {}\", apply_with_log(mul_5, 20));\n" -"}\n" -"```" -msgstr "" +#: src/std-traits/closures.md +#, fuzzy +msgid "\"Calling function on {input}\"" +msgstr "呼叫不安全的函式" -#: src/traits/closures.md:25 -msgid "" -"If you have an `FnOnce`, you may only call it once. It might consume " -"captured values." -msgstr "" +#: src/std-traits/closures.md +msgid "\"add_3: {}\"" +msgstr "\"add_3: {}\"" -#: src/traits/closures.md:27 -msgid "" -"An `FnMut` might mutate captured values, so you can call it multiple times " -"but not concurrently." -msgstr "" +#: src/std-traits/closures.md +msgid "\"accumulate: {}\"" +msgstr "\"accumulate: {}\"" -#: src/traits/closures.md:29 -msgid "" -"An `Fn` neither consumes nor mutates captured values, or perhaps captures " -"nothing at all, so it can be called multiple times concurrently." -msgstr "" +#: src/std-traits/closures.md +msgid "\"multiply_sum: {}\"" +msgstr "\"multiply_sum: {}\"" -#: src/traits/closures.md:43 +#: src/std-traits/closures.md +msgid "" +"An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or " +"perhaps captures nothing at all. It can be called multiple times " +"concurrently." +msgstr "" +"`Fn` (例如 `add_3`) 既不會耗用也不會修改擷取的值,或許 也可說是不會擷取任何" +"值,因此可以多次並行呼叫。" + +#: src/std-traits/closures.md +msgid "" +"An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it " +"multiple times, but not concurrently." +msgstr "" +"`FnMut` (例如 `accumulate`) 可能會修改擷取的值,因此可以多次呼叫 (但不得並行" +"呼叫)。" + +#: src/std-traits/closures.md +msgid "" +"If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It " +"might consume captured values." +msgstr "" +"如果是 `FnOnce` (例如`multiply_sum`),也許就只能呼叫一次,因為這可能會耗用 擷" +"取的值。" + +#: src/std-traits/closures.md msgid "" "`FnMut` is a subtype of `FnOnce`. `Fn` is a subtype of `FnMut` and `FnOnce`. " "I.e. you can use an `FnMut` wherever an `FnOnce` is called for, and you can " @@ -10454,1023 +7245,3212 @@ msgstr "" "說,您可以在任何需要呼叫 `FnOnce` 的地方使用 `FnMut`,而在任何需要呼叫 " "`FnMut` 或 `FnOnce` 的地方 使用 `Fn`。" -#: src/traits/closures.md:36 -msgid "`move` closures only implement `FnOnce`." +#: src/std-traits/closures.md +msgid "" +"When you define a function that takes a closure, you should take `FnOnce` if " +"you can (i.e. you call it once), or `FnMut` else, and last `Fn`. This allows " +"the most flexibility for the caller." +msgstr "" +"定義可接受閉包的函式時,您應盡量採用 `FnOnce` (也就是只呼叫一次),其次是 " +"`FnMut`,最後則是 `Fn`。這種做法可讓呼叫端享有最大彈性。" + +#: src/std-traits/closures.md +msgid "" +"In contrast, when you have a closure, the most flexible you can have is `Fn` " +"(it can be passed everywhere), then `FnMut`, and lastly `FnOnce`." +msgstr "" +"相反地,當有閉包時,最有彈性的就是 `Fn` (可以在任何地方傳遞)、其次是 " +"`FnMut`,最後是 `FnOnce`。" + +#: src/std-traits/closures.md +msgid "" +"The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. " +"`multiply_sum`), depending on what the closure captures." +msgstr "" +"編譯器也會根據閉包擷取到的內容來推論 `Copy` (例如針對 `add_3`) 和 `Clone` (例" +"如 `multiply_sum`)." + +#: src/std-traits/closures.md +msgid "" +"By default, closures will capture by reference if they can. The `move` " +"keyword makes them capture by value." +msgstr "" +"根據預設,閉包會依據參照來擷取內容 (如果可行的話)。`move` 關鍵字則可讓閉包根" +"據值 來擷取內容。" + +#: src/std-traits/closures.md src/smart-pointers/trait-objects.md +msgid "\"{} {}\"" +msgstr "\"{} {}\"" + +#: src/std-traits/closures.md +msgid "\"Hi\"" +msgstr "\"Hi\"" + +#: src/std-traits/closures.md +msgid "\"Greg\"" msgstr "" -#: src/exercises/day-3/morning.md:1 -msgid "Day 3: Morning Exercises" -msgstr "第 3 天:上午練習" - -#: src/exercises/day-3/morning.md:3 -msgid "We will design a classical GUI library traits and trait objects." +#: src/std-traits/exercise.md +msgid "" +"In this example, you will implement the classic [\"ROT13\" cipher](https://" +"en.wikipedia.org/wiki/ROT13). Copy this code to the playground, and " +"implement the missing bits. Only rotate ASCII alphabetic characters, to " +"ensure the result is still valid UTF-8." msgstr "" +"在這個範例中,您將實作傳統的[「ROT13」加密方式](https://zh.wikipedia.org/" +"wiki/ROT13)。請將此程式碼複製到 Playground,並實作缺少的位元。記得僅能旋轉 " +"ASCII 字母字元,確保結果仍為有效的 UTF-8。" -#: src/exercises/day-3/simple-gui.md:3 +#: src/std-traits/exercise.md +msgid "// Implement the `Read` trait for `RotDecoder`.\n" +msgstr "// Implement the `Read` trait for `RotDecoder`.\n" + +#: src/std-traits/exercise.md src/std-traits/solution.md +msgid "\"Gb trg gb gur bgure fvqr!\"" +msgstr "\"Gb trg gb gur bgure fvqr!\"" + +#: src/std-traits/exercise.md src/std-traits/solution.md +msgid "\"To get to the other side!\"" +msgstr "\"To get to the other side!\"" + +#: src/std-traits/exercise.md msgid "" -"Let us design a classical GUI library using our new knowledge of traits and " -"trait objects." -msgstr "我們對特徵和特徵物件有了新的瞭解,現在來設計經典的 GUI 程式庫吧!" - -#: src/exercises/day-3/simple-gui.md:6 -msgid "We will have a number of widgets in our library:" -msgstr "我們的程式庫中會有許多小工具:" - -#: src/exercises/day-3/simple-gui.md:8 -msgid "`Window`: has a `title` and contains other widgets." -msgstr "`Window`:有 `title` 且包含其他小工具。" - -#: src/exercises/day-3/simple-gui.md:9 -msgid "" -"`Button`: has a `label` and a callback function which is invoked when the " -"button is pressed." -msgstr "`Button`:含有 `label` 和回呼函式,按下按鈕就會叫用這個函式。" - -#: src/exercises/day-3/simple-gui.md:11 -msgid "`Label`: has a `label`." -msgstr "`Label`:含有 `label`。" - -#: src/exercises/day-3/simple-gui.md:13 -msgid "The widgets will implement a `Widget` trait, see below." -msgstr "小工具會實作 `Widget` 特徵,請參閱下文。" - -#: src/exercises/day-3/simple-gui.md:15 -msgid "" -"Copy the code below to , fill in the missing " -"`draw_into` methods so that you implement the `Widget` trait:" +"What happens if you chain two `RotDecoder` instances together, each rotating " +"by 13 characters?" msgstr "" -"請將以下程式碼複製到 ,並填入缺少的 `draw_into` " -"方法,以便實作 `Widget` 特徵:" +"如果將兩個 `RotDecoder` 例項鏈結在一起,每個都以 13 個字元旋轉,會怎麼樣?" -#: src/exercises/day-3/simple-gui.md:18 +#: src/std-traits/solution.md +msgid "'A'" +msgstr "'A'" + +#: src/welcome-day-3.md +msgid "Welcome to Day 3" +msgstr "歡迎參加第 3 天課程" + +#: src/welcome-day-3.md +msgid "Today, we will cover:" +msgstr "今天我們將講解以下內容:" + +#: src/welcome-day-3.md msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_imports, unused_variables, dead_code)]\n" -"\n" -"pub trait Widget {\n" -" /// Natural width of `self`.\n" -" fn width(&self) -> usize;\n" -"\n" -" /// Draw the widget into a buffer.\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write);\n" -"\n" -" /// Draw the widget on standard output.\n" -" fn draw(&self) {\n" -" let mut buffer = String::new();\n" -" self.draw_into(&mut buffer);\n" -" println!(\"{buffer}\");\n" -" }\n" -"}\n" -"\n" -"pub struct Label {\n" -" label: String,\n" -"}\n" -"\n" -"impl Label {\n" -" fn new(label: &str) -> Label {\n" -" Label {\n" -" label: label.to_owned(),\n" -" }\n" -" }\n" -"}\n" -"\n" -"pub struct Button {\n" -" label: Label,\n" -" callback: Box,\n" -"}\n" -"\n" -"impl Button {\n" -" fn new(label: &str, callback: Box) -> Button {\n" -" Button {\n" -" label: Label::new(label),\n" -" callback,\n" -" }\n" -" }\n" -"}\n" -"\n" -"pub struct Window {\n" -" title: String,\n" -" widgets: Vec>,\n" -"}\n" -"\n" -"impl Window {\n" -" fn new(title: &str) -> Window {\n" -" Window {\n" -" title: title.to_owned(),\n" -" widgets: Vec::new(),\n" -" }\n" -" }\n" -"\n" -" fn add_widget(&mut self, widget: Box) {\n" -" self.widgets.push(widget);\n" -" }\n" -"\n" -" fn inner_width(&self) -> usize {\n" -" std::cmp::max(\n" -" self.title.chars().count(),\n" -" self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),\n" -" )\n" -" }\n" -"}\n" -"\n" -"\n" -"impl Widget for Label {\n" -" fn width(&self) -> usize {\n" -" unimplemented!()\n" -" }\n" -"\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"impl Widget for Button {\n" -" fn width(&self) -> usize {\n" -" unimplemented!()\n" -" }\n" -"\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"impl Widget for Window {\n" -" fn width(&self) -> usize {\n" -" unimplemented!()\n" -" }\n" -"\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" let mut window = Window::new(\"Rust GUI Demo 1.23\");\n" -" window.add_widget(Box::new(Label::new(\"This is a small text GUI demo." -"\")));\n" -" window.add_widget(Box::new(Button::new(\n" -" \"Click me!\",\n" -" Box::new(|| println!(\"You clicked the button!\")),\n" -" )));\n" -" window.draw();\n" -"}\n" +"Memory management, lifetimes, and the borrow checker: how Rust ensures " +"memory safety." +msgstr "記憶體管理、生命週期和借用檢查器:Rust 如何確保記憶體安全。" + +#: src/welcome-day-3.md +msgid "Smart pointers: standard library pointer types." +msgstr "智慧指標:標準程式庫指標型別。" + +#: src/welcome-day-3.md +msgid "[Welcome](./welcome-day-3.md) (3 minutes)" +msgstr "[歡迎](./welcome-day-3.md) (3 分鐘)" + +#: src/welcome-day-3.md +msgid "[Memory Management](./memory-management.md) (1 hour)" +msgstr "[記憶體管理](./memory-management.md) (1 小時)" + +#: src/welcome-day-3.md +msgid "[Smart Pointers](./smart-pointers.md) (55 minutes)" +msgstr "[智慧指標](./smart-pointers.md) (55 分鐘)" + +#: src/welcome-day-3.md +msgid "" +"Including 10 minute breaks, this session should take about 2 hours and 20 " +"minutes" +msgstr "加上 10 分鐘的休息時間,這個課程大約需要 2 小時 20 分鐘" + +#: src/memory-management.md +msgid "[Review of Program Memory](./memory-management/review.md) (5 minutes)" +msgstr "[檢查程式記憶體](./memory-management/review.md) (5 分鐘)" + +#: src/memory-management.md +msgid "" +"[Approaches to Memory Management](./memory-management/approaches.md) (10 " +"minutes)" +msgstr "[管理記憶體的方法](./memory-management/approaches.md) (10 分鐘)" + +#: src/memory-management.md +msgid "[Ownership](./memory-management/ownership.md) (5 minutes)" +msgstr "[擁有權](./memory-management/ownership.md) (5 分鐘)" + +#: src/memory-management.md +msgid "[Move Semantics](./memory-management/move.md) (5 minutes)" +msgstr "[轉移語意](./memory-management/move.md) (5 分鐘)" + +#: src/memory-management.md +msgid "[Clone](./memory-management/clone.md) (2 minutes)" +msgstr "[複製](./memory-management/clone.md) (2 分鐘)" + +#: src/memory-management.md +msgid "[Copy Types](./memory-management/copy-types.md) (5 minutes)" +msgstr "[拷貝 (Copy) 型別](./memory-management/copy-types.md) (5 分鐘)" + +#: src/memory-management.md +msgid "[Drop](./memory-management/drop.md) (10 minutes)" +msgstr "[拖放](./memory-management/drop.md) (10 分鐘)" + +#: src/memory-management.md +msgid "[Exercise: Builder Type](./memory-management/exercise.md) (20 minutes)" +msgstr "[練習:建構工具型別](./memory-management/exercise.md) (20 分鐘)" + +#: src/memory-management/review.md +msgid "Programs allocate memory in two ways:" +msgstr "程式分配記憶體的方式有兩種:" + +#: src/memory-management/review.md +msgid "Stack: Continuous area of memory for local variables." +msgstr "堆疊 (Stack):本機變數的連續記憶體區域。" + +#: src/memory-management/review.md +msgid "Values have fixed sizes known at compile time." +msgstr "值在編譯期間具有已知的固定大小。" + +#: src/memory-management/review.md +msgid "Extremely fast: just move a stack pointer." +msgstr "相當快速:只需移動堆疊指標。" + +#: src/memory-management/review.md +msgid "Easy to manage: follows function calls." +msgstr "易於管理:追蹤函式呼叫。" + +#: src/memory-management/review.md +msgid "Great memory locality." +msgstr "良好的記憶體區域性。" + +#: src/memory-management/review.md +msgid "Heap: Storage of values outside of function calls." +msgstr "堆積 (Heap):函式呼叫外的值儲存空間。" + +#: src/memory-management/review.md +msgid "Values have dynamic sizes determined at runtime." +msgstr "值在執行階段中以動態方式判斷大小。" + +#: src/memory-management/review.md +msgid "Slightly slower than the stack: some book-keeping needed." +msgstr "速度稍慢於堆疊:需要作一些記錄。" + +#: src/memory-management/review.md +msgid "No guarantee of memory locality." +msgstr "不保證記憶體區域性。" + +#: src/memory-management/review.md +#, fuzzy +msgid "" +"Creating a `String` puts fixed-sized metadata on the stack and dynamically " +"sized data, the actual string, on the heap:" +msgstr "" +"建立 `String` 時,系統會在堆疊上放置固定大小的資料,並在堆積上放置動態調整大" +"小的資料:" + +#: src/memory-management/review.md +msgid "" +"Mention that a `String` is backed by a `Vec`, so it has a capacity and " +"length and can grow if mutable via reallocation on the heap." +msgstr "" +"請說明 `String` 是由 `Vec` 支援,因此具有容量和長度,而且還能成長 (前提是可透" +"過堆積上的重新配置作業進行變動)。" + +#: src/memory-management/review.md +msgid "" +"If students ask about it, you can mention that the underlying memory is heap " +"allocated using the [System Allocator](https://doc.rust-lang.org/std/alloc/" +"struct.System.html) and custom allocators can be implemented using the " +"[Allocator API](https://doc.rust-lang.org/std/alloc/index.html)" +msgstr "" +"如有學員問起,您可以說明基礎記憶體是使用\\[系統配置器\\]配置的堆積,而自訂配" +"置器可以使用\\[配置器 API\\] 實作。" + +#: src/memory-management/review.md +#, fuzzy +msgid "" +"We can inspect the memory layout with `unsafe` Rust. However, you should " +"point out that this is rightfully unsafe!" +msgstr "" +"我們可以使用 `unsafe` 程式碼檢查記憶體配置。不過,您應指出這麼做非常不安全!" + +#: src/memory-management/review.md src/testing/unit-tests.md +msgid "' '" +msgstr "' '" + +#: src/memory-management/review.md +msgid "\"world\"" +msgstr "\"world\"" + +#: src/memory-management/review.md +msgid "" +"// DON'T DO THIS AT HOME! For educational purposes only.\n" +" // String provides no guarantees about its layout, so this could lead " +"to\n" +" // undefined behavior.\n" +msgstr "" +"// DON'T DO THIS AT HOME! For educational purposes only.\n" +" // String provides no guarantees about its layout, so this could lead " +"to\n" +" // undefined behavior.\n" + +#: src/memory-management/review.md +msgid "\"capacity = {capacity}, ptr = {ptr:#x}, len = {len}\"" +msgstr "\"capacity = {capacity}, ptr = {ptr:#x}, len = {len}\"" + +#: src/memory-management/approaches.md +msgid "Traditionally, languages have fallen into two broad categories:" +msgstr "傳統上,語言大致可分為兩種:" + +#: src/memory-management/approaches.md +msgid "Full control via manual memory management: C, C++, Pascal, ..." +msgstr "透過手動管理記憶體,取得完整掌控權:C、C++、Pascal..." + +#: src/memory-management/approaches.md +msgid "Programmer decides when to allocate or free heap memory." +msgstr "程式設計師會決定何時分配或釋出堆積記憶體。" + +#: src/memory-management/approaches.md +msgid "" +"Programmer must determine whether a pointer still points to valid memory." +msgstr "程式設計師必須判斷指標是否仍指向有效記憶體。" + +#: src/memory-management/approaches.md +msgid "Studies show, programmers make mistakes." +msgstr "研究顯示,程式設計師難免會出錯。" + +#: src/memory-management/approaches.md +msgid "" +"Full safety via automatic memory management at runtime: Java, Python, Go, " +"Haskell, ..." +msgstr "" +"透過在執行階段中自動管理記憶體,取得完整安全性:Java、Python、Go、Haskell..." + +#: src/memory-management/approaches.md +msgid "" +"A runtime system ensures that memory is not freed until it can no longer be " +"referenced." +msgstr "執行階段系統會確保在可以參照記憶體之後,才釋出記憶體。" + +#: src/memory-management/approaches.md +msgid "" +"Typically implemented with reference counting, garbage collection, or RAII." +msgstr "通常透過參照計算、垃圾收集或 RAII 的方式實作。" + +#: src/memory-management/approaches.md +msgid "Rust offers a new mix:" +msgstr "Rust 則融合這兩種做法:" + +#: src/memory-management/approaches.md +msgid "" +"Full control _and_ safety via compile time enforcement of correct memory " +"management." +msgstr "" +"透過正確的記憶體管理編譯時間強制執行措施,「同時」取得完整的掌控權和安全性。" + +#: src/memory-management/approaches.md +msgid "It does this with an explicit ownership concept." +msgstr "Rust 運用明確所有權的概念實現這一點。" + +#: src/memory-management/approaches.md +msgid "" +"This slide is intended to help students coming from other languages to put " +"Rust in context." +msgstr "這張投影片的目的,在於協助其他語言的學員瞭解 Rust。" + +#: src/memory-management/approaches.md +msgid "" +"C must manage heap manually with `malloc` and `free`. Common errors include " +"forgetting to call `free`, calling it multiple times for the same pointer, " +"or dereferencing a pointer after the memory it points to has been freed." +msgstr "" +"如果是 C 語言,必須透過 `malloc` 和 `free` 手動管理堆積。常見的錯誤包括忘記呼" +"叫 `free`、針對同一指標多次呼叫 `free`,或在其指向的記憶體釋出後取消參照指" +"標。" + +#: src/memory-management/approaches.md +msgid "" +"C++ has tools like smart pointers (`unique_ptr`, `shared_ptr`) that take " +"advantage of language guarantees about calling destructors to ensure memory " +"is freed when a function returns. It is still quite easy to mis-use these " +"tools and create similar bugs to C." +msgstr "" +"C++ 提供智慧指標 (`unique_ptr`、`shared_ptr`) 等工具,可利用有關呼叫解構函式" +"的語言保證,確保在函式傳回時釋出記憶體。但這些工具仍很容易遭到濫用,並且會產" +"生類似 C 語言中的那些錯誤。" + +#: src/memory-management/approaches.md +msgid "" +"Java, Go, and Python rely on the garbage collector to identify memory that " +"is no longer reachable and discard it. This guarantees that any pointer can " +"be dereferenced, eliminating use-after-free and other classes of bugs. But, " +"GC has a runtime cost and is difficult to tune properly." +msgstr "" +"Java、Go 和 Python 會利用垃圾收集器來識別並捨棄無法再存取的記憶體。這能確保任" +"何指標都可以取消參照,進而消除 UAF (使用已釋放記憶體)和其他類別的錯誤。不過," +"GC 會耗費執行階段成本,且很難正確調整。" + +#: src/memory-management/approaches.md +msgid "" +"Rust's ownership and borrowing model can, in many cases, get the performance " +"of C, with alloc and free operations precisely where they are required -- " +"zero cost. It also provides tools similar to C++'s smart pointers. When " +"required, other options such as reference counting are available, and there " +"are even third-party crates available to support runtime garbage collection " +"(not covered in this class)." +msgstr "" +"在許多情況下,Rust 的擁有權和借用模型效能都能媲美 C 語言,並在必要處精準分配" +"及釋放,達成零成本作業。Rust 也提供類似 C++ 智慧指標的工具。如有需要,您還可" +"以使用參照計數等其他選項,而且甚至還有第三方 Crate,可支援執行階段的垃圾收集" +"作業 (本課程不會討論這部分)。" + +#: src/memory-management/ownership.md +msgid "" +"All variable bindings have a _scope_ where they are valid and it is an error " +"to use a variable outside its scope:" +msgstr "所有變數繫結都會在特定「範圍」內有效,在範圍外使用變數會是錯誤:" + +#: src/memory-management/ownership.md +#, fuzzy +msgid "" +"We say that the variable _owns_ the value. Every Rust value has precisely " +"one owner at all times." +msgstr "我們會說變數「擁有」值。" + +#: src/memory-management/ownership.md +#, fuzzy +msgid "" +"At the end of the scope, the variable is _dropped_ and the data is freed. A " +"destructor can run here to free up resources." +msgstr "範圍結束時,變數會遭到「捨棄」,資料也會釋放。" + +#: src/memory-management/ownership.md +msgid "" +"Students familiar with garbage-collection implementations will know that a " +"garbage collector starts with a set of \"roots\" to find all reachable " +"memory. Rust's \"single owner\" principle is a similar idea." +msgstr "" +"熟悉垃圾回收實作的學員會知道,垃圾回收器是從一組「根」開始尋找所有可存取的記" +"憶體。Rust 的「單一擁有者」原則也是類似的概念。" + +#: src/memory-management/move.md +#, fuzzy +msgid "An assignment will transfer _ownership_ between variables:" +msgstr "指派會在變數之間轉移所有權:" + +#: src/memory-management/move.md +msgid "\"Hello!\"" +msgstr "\"Hello!\"" + +#: src/memory-management/move.md src/slices-and-lifetimes/str.md +msgid "\"s2: {s2}\"" +msgstr "\"s2: {s2}\"" + +#: src/memory-management/move.md +msgid "// println!(\"s1: {s1}\");\n" +msgstr "// println!(\"s1: {s1}\");\n" + +#: src/memory-management/move.md +msgid "The assignment of `s1` to `s2` transfers ownership." +msgstr "將 `s1` 指派給 `s2` 會轉移所有權。" + +#: src/memory-management/move.md +#, fuzzy +msgid "When `s1` goes out of scope, nothing happens: it does not own anything." +msgstr "當 `s1` 超出範圍時,系統不會執行任何動作,因為 `s1` 沒有所有權。" + +#: src/memory-management/move.md +msgid "When `s2` goes out of scope, the string data is freed." +msgstr "當 `s2` 超出範圍時,系統會釋放字串資料。" + +#: src/memory-management/move.md +msgid "Before move to `s2`:" +msgstr "移至 `s2` 前:" + +#: src/memory-management/move.md +msgid "After move to `s2`:" +msgstr "移至 `s2` 後:" + +#: src/memory-management/move.md +#, fuzzy +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 \"(inaccessible)\" : : :\n" +": +-----------+-------+ : : +----+----+----+----+----+----+ :\n" +": | ptr | o---+---+--+--+-->| H | e | l | l | o | ! | :\n" +": | len | 4 | : | : +----+----+----+----+----+----+ :\n" +": | capacity | 4 | : | : :\n" +": +-----------+-------+ : | : :\n" +": : | `- - - - - - - - - - - - - - - - - - -'\n" +": s2 : |\n" +": +-----------+-------+ : |\n" +": | ptr | o---+---+--'\n" +": | len | 4 | :\n" +": | capacity | 4 | :\n" +": +-----------+-------+ :\n" +": :\n" +"`- - - - - - - - - - - - - -'\n" "```" msgstr "" - -#: src/exercises/day-3/simple-gui.md:130 -msgid "The output of the above program can be something simple like this:" -msgstr "上方程式的輸出內容可以很簡單,像下面這樣:" - -#: src/exercises/day-3/simple-gui.md:132 -msgid "" -"```text\n" -"========\n" -"Rust GUI Demo 1.23\n" -"========\n" -"\n" -"This is a small text GUI demo.\n" -"\n" -"| Click me! |\n" -"```" -msgstr "" - -#: src/exercises/day-3/simple-gui.md:142 -msgid "" -"If you want to draw aligned text, you can use the [fill/alignment](https://" -"doc.rust-lang.org/std/fmt/index.html#fillalignment) formatting operators. In " -"particular, notice how you can pad with different characters (here a `'/'`) " -"and how you can control alignment:" -msgstr "" -"如要繪製對齊的文字,可以使用 [fill/alignment](https://doc.rust-lang.org/std/" -"fmt/index.html#fillalignment) 格式化運算子。請特別注意如何使用不同的字元 (此" -"處為 `'/'`) 設定邊框間距,以及可以如何控制對齊方式:" - -#: src/exercises/day-3/simple-gui.md:147 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let width = 10;\n" -" println!(\"left aligned: |{:/width$}|\", \"foo\");\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-3/simple-gui.md:156 -msgid "" -"Using such alignment tricks, you can for example produce output like this:" -msgstr "使用這種對齊技巧,您可以產生如下的輸出內容:" - -#: src/exercises/day-3/simple-gui.md:158 -msgid "" -"```text\n" -"+--------------------------------+\n" -"| Rust GUI Demo 1.23 |\n" -"+================================+\n" -"| This is a small text GUI demo. |\n" -"| +-----------+ |\n" -"| | Click me! | |\n" -"| +-----------+ |\n" -"+--------------------------------+\n" -"```" -msgstr "" - -#: src/error-handling.md:3 -msgid "Error handling in Rust is done using explicit control flow:" -msgstr "在 Rust 中,是透過明確的控制流程完成錯誤處理作業:" - -#: src/error-handling.md:5 -msgid "Functions that can have errors list this in their return type," -msgstr "可能含有錯誤的函式會在回傳型別中列出相關資訊。" - -#: src/error-handling.md:6 -msgid "There are no exceptions." -msgstr "沒有任何例外。" - -#: src/error-handling/panics.md:3 -msgid "Rust will trigger a panic if a fatal error happens at runtime:" -msgstr "如果執行階段發生重大錯誤,Rust 就會觸發恐慌:" - -#: src/error-handling/panics.md:5 -msgid "" -"```rust,editable,should_panic\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" println!(\"v[100]: {}\", v[100]);\n" -"}\n" -"```" -msgstr "" -"```rust,editable,should_panic\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" println!(\"v[100]: {}\", v[100]);\n" -"}\n" +"```bob\n" +" 堆疊 堆積\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 \"(inaccessible)\" : : :\n" +": +-----------+-------+ : : +----+----+----+----+ :\n" +": | ptr | o---+---+--+--+-->| R | u | s | t | :\n" +": | len | 4 | : | : +----+----+----+----+ :\n" +": | capacity | 4 | : | : :\n" +": +-----------+-------+ : | : :\n" +": : | `- - - - - - - - - - - - - -'\n" +": s2 : |\n" +": +-----------+-------+ : |\n" +": | ptr | o---+---+--'\n" +": | len | 4 | :\n" +": | capacity | 4 | :\n" +": +-----------+-------+ :\n" +": :\n" +"`- - - - - - - - - - - - - -'\n" "```" -#: src/error-handling/panics.md:12 -msgid "Panics are for unrecoverable and unexpected errors." -msgstr "恐慌代表發生無法復原的非預期錯誤。" - -#: src/error-handling/panics.md:13 -msgid "Panics are symptoms of bugs in the program." -msgstr "恐慌可以反映程式中的錯誤。" - -#: src/error-handling/panics.md:14 +#: src/memory-management/move.md msgid "" -"Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable." -msgstr "如果無法接受程式崩潰,請使用不會觸發恐慌的 API,例如 `Vec::get`。" +"When you pass a value to a function, the value is assigned to the function " +"parameter. This transfers ownership:" +msgstr "將值傳遞至函式時,該值會指派給函式參數。這麼做會轉移所有權:" -#: src/error-handling/panic-unwind.md:1 -msgid "Catching the Stack Unwinding" -msgstr "擷取解開堆疊的動作" +#: src/memory-management/move.md +msgid "\"Hello {name}\"" +msgstr "\"Hello {name}\"" -#: src/error-handling/panic-unwind.md:3 +#: src/memory-management/move.md src/android/interoperability/java.md +msgid "\"Alice\"" +msgstr "\"Alice\"" + +#: src/memory-management/move.md +msgid "// say_hello(name);\n" +msgstr "// say_hello(name);\n" + +#: src/memory-management/move.md msgid "" -"By default, a panic will cause the stack to unwind. The unwinding can be " -"caught:" -msgstr "根據預設,恐慌會造成解開堆疊。您可以擷取這類動作:" +"Mention that this is the opposite of the defaults in C++, which copies by " +"value unless you use `std::move` (and the move constructor is defined!)." +msgstr "" +"請說明這與 C++ 中的預設情形相反:您必須使用 `std::move`,且已定義移動建構函" +"式,系統才會根據值進行複製。" -#: src/error-handling/panic-unwind.md:5 +#: src/memory-management/move.md msgid "" -"```rust,editable\n" -"use std::panic;\n" -"\n" -"let result = panic::catch_unwind(|| {\n" -" println!(\"hello!\");\n" -"});\n" -"assert!(result.is_ok());\n" -"\n" -"let result = panic::catch_unwind(|| {\n" -" panic!(\"oh no!\");\n" -"});\n" -"assert!(result.is_err());\n" +"It is only the ownership that moves. Whether any machine code is generated " +"to manipulate the data itself is a matter of optimization, and such copies " +"are aggressively optimized away." +msgstr "" +"只有擁有權才會轉移。是否產生任何機器碼來操控資料本身是一個最優化問題,而系統" +"會主動將這些副本最優化。" + +#: src/memory-management/move.md +msgid "" +"Simple values (such as integers) can be marked `Copy` (see later slides)." +msgstr "簡單的值 (例如整數) 可標示為 `Copy` (請參閱後續投影片)。" + +#: src/memory-management/move.md +msgid "In Rust, clones are explicit (by using `clone`)." +msgstr "在 Rust 中,克隆作業皆為明確設定,方法為使用 `clone`。" + +#: src/memory-management/move.md +msgid "In the `say_hello` example:" +msgstr "在 `say_hello` 範例中:" + +#: src/memory-management/move.md +msgid "" +"With the first call to `say_hello`, `main` gives up ownership of `name`. " +"Afterwards, `name` cannot be used anymore within `main`." +msgstr "" +"首次呼叫 `say_hello` 時,`main` 會放棄 `name` 的所有權。之後,`name` 就無法" +"在 `main` 內使用。" + +#: src/memory-management/move.md +msgid "" +"The heap memory allocated for `name` will be freed at the end of the " +"`say_hello` function." +msgstr "為 `name` 配置的堆積記憶體會在 `say_hello` 函式結束時釋放。" + +#: src/memory-management/move.md +msgid "" +"`main` can retain ownership if it passes `name` as a reference (`&name`) and " +"if `say_hello` accepts a reference as a parameter." +msgstr "" +"如果 `main` 以參照的形式傳送 `name` (`&name`),且 `say_hello` 能以參數的形式" +"接受參照,`main` 就可以保留所有權。" + +#: src/memory-management/move.md +msgid "" +"Alternatively, `main` can pass a clone of `name` in the first call (`name." +"clone()`)." +msgstr "另外,`main` 可在首次呼叫 (`name.clone()`) 中傳遞 `name` 的克隆。" + +#: src/memory-management/move.md +msgid "" +"Rust makes it harder than C++ to inadvertently create copies by making move " +"semantics the default, and by forcing programmers to make clones explicit." +msgstr "" +"在 Rust 中,移動語意為預設做法,且強制規定程式設計師必須明確設定克隆,因此不" +"小心建立副本的可能性就會低於在 C++ 中。" + +#: src/memory-management/move.md +#, fuzzy +msgid "Defensive Copies in Modern C++" +msgstr "現代 C++ 中的雙重釋放" + +#: src/memory-management/move.md +msgid "Modern C++ solves this differently:" +msgstr "現代 C++ 可使用不同方式解決這個問題:" + +#: src/memory-management/move.md +msgid "\"Cpp\"" +msgstr "\"Cpp\"" + +#: src/memory-management/move.md +msgid "// Duplicate the data in s1.\n" +msgstr "// Duplicate the data in s1.\n" + +#: src/memory-management/move.md +msgid "" +"The heap data from `s1` is duplicated and `s2` gets its own independent copy." +msgstr "`s1` 的堆積資料會重複,`s2` 會取得專屬的獨立副本。" + +#: src/memory-management/move.md +msgid "When `s1` and `s2` go out of scope, they each free their own memory." +msgstr "當 `s1` 和 `s2` 超出範圍時,皆會釋放自己的記憶體。" + +#: src/memory-management/move.md +msgid "Before copy-assignment:" +msgstr "複製指派前:" + +#: src/memory-management/move.md +msgid "After copy-assignment:" +msgstr "複製指派後:" + +#: src/memory-management/move.md +msgid "" +"C++ has made a slightly different choice than Rust. Because `=` copies data, " +"the string data has to be cloned. Otherwise we would get a double-free when " +"either string goes out of scope." +msgstr "" +"C++ 提供的選擇與 Rust 略有不同。由於 `=` 會複製資料,所以字串資料一定要完成複" +"製。否則,假如其中任一字串超出範圍,就會導致重複釋放的結果。" + +#: src/memory-management/move.md +msgid "" +"C++ also has [`std::move`](https://en.cppreference.com/w/cpp/utility/move), " +"which is used to indicate when a value may be moved from. If the example had " +"been `s2 = std::move(s1)`, no heap allocation would take place. After the " +"move, `s1` would be in a valid but unspecified state. Unlike Rust, the " +"programmer is allowed to keep using `s1`." +msgstr "" +"C++ 也提供 [`std::move`](https://en.cppreference.com/w/cpp/utility/move),用" +"於指出何時可以轉移特定值。例如假設是 `s2 = std::move(s1)`,就不會發生堆積分配" +"的情形。轉移之後,`s1` 會處於有效但未指定的狀態。與 Rust 不同的是,程式設計師" +"可以繼續使用 `s1`。" + +#: src/memory-management/move.md +msgid "" +"Unlike Rust, `=` in C++ can run arbitrary code as determined by the type " +"which is being copied or moved." +msgstr "" +"C++ 中的 `=` 可以依照要複製或轉移的型別來執行任何程式碼,這點與 Rust 不同。" + +#: src/memory-management/clone.md +msgid "Clone" +msgstr "`Clone` 複製" + +#: src/memory-management/clone.md +msgid "" +"Sometimes you _want_ to make a copy of a value. The `Clone` trait " +"accomplishes this." +msgstr "有時候,您可能會「想要」複製一個值。`Clone` 特徵可完成這項作業。" + +#: src/memory-management/clone.md +msgid "" +"The idea of `Clone` is to make it easy to spot where heap allocations are " +"occurring. Look for `.clone()` and a few others like `Vec::new` or `Box::" +"new`." +msgstr "" +"`Clone` 的概念是要輕鬆找出堆積分配量的發生位置。請尋找 `.clone()` 和 `Vec::" +"new` 或 `Box::new` 等其他字詞。" + +#: src/memory-management/clone.md +msgid "" +"It's common to \"clone your way out\" of problems with the borrow checker, " +"and return later to try to optimize those clones away." +msgstr "" +"我們往往會使用借用檢查器「複製解決問題的方法」,稍後再回來試著將這些複製內容" +"最佳化。" + +#: src/memory-management/copy-types.md +msgid "" +"While move semantics are the default, certain types are copied by default:" +msgstr "雖然移動語意是預設做法,但某些型別的預設做法為複製:" + +#: src/memory-management/copy-types.md +msgid "These types implement the `Copy` trait." +msgstr "這些型別會實作 `Copy` 特徵。" + +#: src/memory-management/copy-types.md +msgid "You can opt-in your own types to use copy semantics:" +msgstr "您可以自行選擇加入型別,使用複製語意的做法:" + +#: src/memory-management/copy-types.md +msgid "After the assignment, both `p1` and `p2` own their own data." +msgstr "指派後,`p1` 和 `p2` 都會擁有自己的資料。" + +#: src/memory-management/copy-types.md +msgid "We can also use `p1.clone()` to explicitly copy the data." +msgstr "我們也能使用 `p1.clone()` 明確複製資料。" + +#: src/memory-management/copy-types.md +msgid "Copying and cloning are not the same thing:" +msgstr "複製和克隆並不相同:" + +#: src/memory-management/copy-types.md +msgid "" +"Copying refers to bitwise copies of memory regions and does not work on " +"arbitrary objects." +msgstr "複製是指記憶體區域的按位元複製作業,不適用於任意物件。" + +#: src/memory-management/copy-types.md +msgid "" +"Copying does not allow for custom logic (unlike copy constructors in C++)." +msgstr "複製不允許用於自訂邏輯,這與 C++ 中的複製建構函式不同。" + +#: src/memory-management/copy-types.md +msgid "" +"Cloning is a more general operation and also allows for custom behavior by " +"implementing the `Clone` trait." +msgstr "克隆是較廣泛的作業,而且只要實作 `Clone` 特徵,即允許用於自訂行為。" + +#: src/memory-management/copy-types.md +msgid "Copying does not work on types that implement the `Drop` trait." +msgstr "複製不適用於實作 `Drop` 特徵的型別。" + +#: src/memory-management/copy-types.md +msgid "In the above example, try the following:" +msgstr "在上述範例中,請嘗試下列操作:" + +#: src/memory-management/copy-types.md +msgid "" +"Add a `String` field to `struct Point`. It will not compile because `String` " +"is not a `Copy` type." +msgstr "" +"將 `String` 欄位新增至 `struct Point`。由於 `String` 不屬於 `Copy` 型別,因此" +"不會編譯。" + +#: src/memory-management/copy-types.md +#, fuzzy +msgid "" +"Remove `Copy` from the `derive` attribute. The compiler error is now in the " +"`println!` for `p1`." +msgstr "" +"從 `derive` 屬性中移除 `Copy`。編譯器錯誤現在位於 `p1` 的 `println!` 中。" + +#: src/memory-management/copy-types.md +msgid "Show that it works if you clone `p1` instead." +msgstr "示範如果改為克隆 `p1`,就能正常運作。" + +#: src/memory-management/drop.md +msgid "The `Drop` Trait" +msgstr "`Drop` 特徵" + +#: src/memory-management/drop.md +msgid "" +"Values which implement [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop." +"html) can specify code to run when they go out of scope:" +msgstr "" +"如果值實作了 [`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html),即" +"可在超出範圍時指定要執行哪個程式碼:" + +#: src/memory-management/drop.md +msgid "\"Dropping {}\"" +msgstr "\"Dropping {}\"" + +#: src/memory-management/drop.md src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"a\"" +msgstr "\"a\"" + +#: src/memory-management/drop.md src/android/testing/googletest.md +msgid "\"b\"" +msgstr "\"b\"" + +#: src/memory-management/drop.md +msgid "\"c\"" +msgstr "\"c\"" + +#: src/memory-management/drop.md +msgid "\"d\"" +msgstr "\"d\"" + +#: src/memory-management/drop.md +msgid "\"Exiting block B\"" +msgstr "\"Exiting block B\"" + +#: src/memory-management/drop.md +msgid "\"Exiting block A\"" +msgstr "\"Exiting block A\"" + +#: src/memory-management/drop.md +msgid "\"Exiting main\"" +msgstr "\"Exiting main\"" + +#: src/memory-management/drop.md +msgid "Note that `std::mem::drop` is not the same as `std::ops::Drop::drop`." +msgstr "請注意,`std::mem::drop` 和 `std::ops::Drop::drop` 不同。" + +#: src/memory-management/drop.md +msgid "Values are automatically dropped when they go out of scope." +msgstr "值超出範圍時,系統會自動捨棄。" + +#: src/memory-management/drop.md +msgid "" +"When a value is dropped, if it implements `std::ops::Drop` then its `Drop::" +"drop` implementation will be called." +msgstr "" +"捨棄值時,如果值實作的是 `std::ops::Drop`,系統會呼叫值的 `Drop::drop` 實作。" + +#: src/memory-management/drop.md +msgid "" +"All its fields will then be dropped too, whether or not it implements `Drop`." +msgstr "如此一來,無論值是否實作 `Drop`,系統都會一併捨棄值的所有欄位。" + +#: src/memory-management/drop.md +msgid "" +"`std::mem::drop` is just an empty function that takes any value. The " +"significance is that it takes ownership of the value, so at the end of its " +"scope it gets dropped. This makes it a convenient way to explicitly drop " +"values earlier than they would otherwise go out of scope." +msgstr "" +"`std::mem::drop` 只是一個可接受任何值的空白函式。此函式之所以重要,是能夠取得" +"值的擁有權,因此在其範圍結束時會遭到捨棄。這有利於在值超出範圍之前,明確捨棄" +"這些值。" + +#: src/memory-management/drop.md +msgid "" +"This can be useful for objects that do some work on `drop`: releasing locks, " +"closing files, etc." +msgstr "" +"如果物件會對 `drop` 執行某些工作 (例如釋放鎖、關閉檔案等),這就相當實用。" + +#: src/memory-management/drop.md +msgid "Why doesn't `Drop::drop` take `self`?" +msgstr "為什麼 `Drop::drop` 不使用 `self`?" + +#: src/memory-management/drop.md +msgid "" +"Short-answer: If it did, `std::mem::drop` would be called at the end of the " +"block, resulting in another call to `Drop::drop`, and a stack overflow!" +msgstr "" +"簡答:如果這樣的話,系統會在 區塊結尾呼叫 `std::mem::drop`,進而觸發另一個對 " +"`Drop::drop` 的呼叫並造成堆疊 溢位!" + +#: src/memory-management/drop.md +msgid "Try replacing `drop(a)` with `a.drop()`." +msgstr "請嘗試將 `drop(a)` 替換為 `a.drop()`。" + +#: src/memory-management/exercise.md +msgid "" +"In this example, we will implement a complex data type that owns all of its " +"data. We will use the \"builder pattern\" to support building a new value " +"piece-by-piece, using convenience functions." +msgstr "" +"在本範例中,我們將實作一個包含自身所有資料的複雜資料型別。透過「建構工具模" +"式」,我們會以便利函式逐段建構新值。" + +#: src/memory-management/exercise.md +msgid "Fill in the missing pieces." +msgstr "請填補缺漏的片段。" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "/// A representation of a software package.\n" +msgstr "/// A representation of a software package.\n" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "" +"/// Return a representation of this package as a dependency, for use in\n" +" /// building other packages.\n" +msgstr "" +"/// Return a representation of this package as a dependency, for use in\n" +" /// building other packages.\n" + +#: src/memory-management/exercise.md +msgid "\"1\"" +msgstr "\"1\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "" +"/// A builder for a Package. Use `build()` to create the `Package` itself.\n" +msgstr "" +"/// A builder for a Package. Use `build()` to create the `Package` itself.\n" + +#: src/memory-management/exercise.md +msgid "\"2\"" +msgstr "\"2\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "/// Set the package version.\n" +msgstr "/// Set the package version.\n" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "/// Set the package authors.\n" +msgstr "/// Set the package authors.\n" + +#: src/memory-management/exercise.md +msgid "\"3\"" +msgstr "\"3\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "/// Add an additional dependency.\n" +msgstr "/// Add an additional dependency.\n" + +#: src/memory-management/exercise.md +msgid "\"4\"" +msgstr "\"4\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "/// Set the language. If not set, language defaults to None.\n" +msgstr "/// Set the language. If not set, language defaults to None.\n" + +#: src/memory-management/exercise.md +msgid "\"5\"" +msgstr "\"5\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"base64\"" +msgstr "\"base64\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"0.13\"" +msgstr "\"0.13\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"base64: {base64:?}\"" +msgstr "\"base64: {base64:?}\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"log\"" +msgstr "\"log\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"0.4\"" +msgstr "\"0.4\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"log: {log:?}\"" +msgstr "\"log: {log:?}\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"serde\"" +msgstr "\"serde\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"djmitche\"" +msgstr "\"djmitche\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"4.0\"" +msgstr "\"4.0\"" + +#: src/memory-management/exercise.md src/memory-management/solution.md +msgid "\"serde: {serde:?}\"" +msgstr "\"serde: {serde:?}\"" + +#: src/memory-management/solution.md +msgid "\"0.1\"" +msgstr "\"0.1\"" + +#: src/smart-pointers.md +msgid "[Box" +msgstr "[Box" + +#: src/smart-pointers.md +msgid "](./smart-pointers/box.md) (10 minutes)" +msgstr "](./smart-pointers/box.md) (10 分鐘)" + +#: src/smart-pointers.md +msgid "[Rc](./smart-pointers/rc.md) (5 minutes)" +msgstr "[Rc](./smart-pointers/rc.md) (5 分鐘)" + +#: src/smart-pointers.md +msgid "[Trait Objects](./smart-pointers/trait-objects.md) (10 minutes)" +msgstr "[特徵物件](./smart-pointers/trait-objects.md) (10 分鐘)" + +#: src/smart-pointers.md +msgid "[Exercise: Binary Tree](./smart-pointers/exercise.md) (30 minutes)" +msgstr "[練習:二元樹](./smart-pointers/exercise.md) (30 分鐘)" + +#: src/smart-pointers.md src/error-handling.md +msgid "This segment should take about 55 minutes" +msgstr "講解這個主題大約需要 55 分鐘" + +#: src/smart-pointers/box.md +msgid "" +"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) is an owned " +"pointer to data on the heap:" +msgstr "" +"[`Box`](https://doc.rust-lang.org/std/boxed/struct.Box.html) 是具有所有權的指" +"向堆積上的資料的指標:" + +#: src/smart-pointers/box.md +msgid "\"five: {}\"" +msgstr "\"five: {}\"" + +#: src/smart-pointers/box.md +msgid "" +"`Box` implements `Deref`, which means that you can [call " +"methods from `T` directly on a `Box`](https://doc.rust-lang.org/std/ops/" +"trait.Deref.html#more-on-deref-coercion)." +msgstr "" +"`Box` 會實作 `Deref`。也就是說,您可以[直接在 `Box` 上透過 " +"`T` 呼叫方法](https://doc.rust-lang.org/std/ops/trait.Deref.html#more-on-" +"deref-coercion)。" + +#: src/smart-pointers/box.md +msgid "" +"Recursive data types or data types with dynamic sizes need to use a `Box`:" +msgstr "遞迴資料型別或含有動態大小的資料型別必須使用 `Box`:" + +#: src/smart-pointers/box.md +msgid "/// A non-empty list: first element and the rest of the list.\n" +msgstr "/// A non-empty list: first element and the rest of the list.\n" + +#: src/smart-pointers/box.md +msgid "/// An empty list.\n" +msgstr "/// An empty list.\n" + +#: src/smart-pointers/box.md +msgid "\"{list:?}\"" +msgstr "\"{list:?}\"" + +#: src/smart-pointers/box.md +#, fuzzy +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - - . .- - - - - - - - - - - - - - - - - - - - " +"- - - - -.\n" +": : : :\n" +": " +"list : : :\n" +": +---------+----+----+ : : +---------+----+----+ +------+----" +"+----+ :\n" +": | Element | 1 | o--+----+-----+--->| Element | 2 | o--+--->| Nil | // " +"| // | :\n" +": +---------+----+----+ : : +---------+----+----+ +------+----" +"+----+ :\n" +": : : :\n" +": : : :\n" +"'- - - - - - - - - - - - - - ' '- - - - - - - - - - - - - - - - - - - - " +"- - - - -'\n" "```" msgstr "" -"```rust,editable\n" -"use std::panic;\n" -"\n" -"let result = panic::catch_unwind(|| {\n" -" println!(\"hello!\");\n" -"});\n" -"assert!(result.is_ok());\n" -"\n" -"let result = panic::catch_unwind(|| {\n" -" panic!(\"oh no!\");\n" -"});\n" -"assert!(result.is_err());\n" +"```bob\n" +" 堆疊 堆積\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+----+----+ :\n" +": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" +": | len | 5 | : : +----+----+----+----+----+ :\n" +": | capacity | 5 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - - - - - -'\n" +"`- - - - - - - - - - - - - -'\n" "```" -#: src/error-handling/panic-unwind.md:21 +#: src/smart-pointers/box.md +#, fuzzy msgid "" -"This can be useful in servers which should keep running even if a single " -"request crashes." +"`Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be " +"not null." msgstr "" -"如果伺服器需要持續運作 (即使有單一要求崩潰也不例外),這種做法就能派上用場。" +"`Box` 就像是 C++ 中的 `std::unique_ptr`,兩者的差別在於 `Box` 不會是空值。" -#: src/error-handling/panic-unwind.md:23 -msgid "This does not work if `panic = 'abort'` is set in your `Cargo.toml`." -msgstr "如果您在 `Cargo.toml` 中設定 `panic = 'abort'`,就無法採取此做法。" +#: src/smart-pointers/box.md +msgid "A `Box` can be useful when you:" +msgstr "在以下情況下,您可以使用 `Box`:" -#: src/error-handling/result.md:1 -msgid "Structured Error Handling with `Result`" -msgstr "使用 `Result` 進行結構化錯誤處理" - -#: src/error-handling/result.md:3 +#: src/smart-pointers/box.md msgid "" -"We have already seen the `Result` enum. This is used pervasively when errors " -"are expected as part of normal operation:" +"have a type whose size that can't be known at compile time, but the Rust " +"compiler wants to know an exact size." +msgstr "編譯時遇到不知道大小為何的型別,但 Rust 編譯器需要知道確切大小。" + +#: src/smart-pointers/box.md +msgid "" +"want to transfer ownership of a large amount of data. To avoid copying large " +"amounts of data on the stack, instead store the data on the heap in a `Box` " +"so only the pointer is moved." msgstr "" -"我們先前介紹了 `Result` 列舉。當正常運作過程中預期發生錯誤時,普遍都會使用這" -"個列舉:" +"想要轉移大量資料的所有權。為避免在堆疊上複製大量資料,請改將資料儲存在 `Box` " +"的堆積上,這樣系統就只會移動指標。" -#: src/error-handling/result.md:6 +#: src/smart-pointers/box.md +#, fuzzy msgid "" -"```rust,editable\n" -"use std::fs::File;\n" -"use std::io::Read;\n" -"\n" -"fn main() {\n" -" let file = File::open(\"diary.txt\");\n" -" match file {\n" -" Ok(mut file) => {\n" -" let mut contents = String::new();\n" -" file.read_to_string(&mut contents);\n" -" println!(\"Dear diary: {contents}\");\n" -" },\n" -" Err(err) => {\n" -" println!(\"The diary could not be opened: {err}\");\n" -" }\n" -" }\n" -"}\n" +"If `Box` was not used and we attempted to embed a `List` directly into the " +"`List`, the compiler would not be able to compute a fixed size for the " +"struct in memory (the `List` would be of infinite size)." +msgstr "" +"如果這裡未使用 `Box`,且我們要將 `List` 直接嵌入 `List`,編譯器就不會計算出固" +"定的結構體記憶體大小,結構體看起來會像是無限大。" + +#: src/smart-pointers/box.md +msgid "" +"`Box` solves this problem as it has the same size as a regular pointer and " +"just points at the next element of the `List` in the heap." +msgstr "" +"`Box` 大小與一般指標相同,並且只會指向堆積中的下一個 `List` 元素,因此可以解" +"決這個問題。" + +#: src/smart-pointers/box.md +#, fuzzy +msgid "" +"Remove the `Box` in the List definition and show the compiler error. We get " +"the message \"recursive without indirection\", because for data recursion, " +"we have to use indirection, a `Box` or reference of some kind, instead of " +"storing the value directly." +msgstr "" +"將 `Box` 從 List 定義中移除後,畫面上會顯示編譯器錯誤。如果您看到「Recursive " +"with indirection」錯誤訊息,建議您使用 Box 或其他種類的參考,而不是直接儲存" +"值。" + +#: src/smart-pointers/box.md +msgid "Niche Optimization" +msgstr "區位最佳化" + +#: src/smart-pointers/box.md +msgid "" +"A `Box` cannot be empty, so the pointer is always valid and non-`null`. This " +"allows the compiler to optimize the memory layout:" +msgstr "" +"`Box` 不能空白,因此指標會一律有效,而且不會是 `null`。這樣一來,編譯器可以將" +"記憶體配置最佳化:" + +#: src/smart-pointers/box.md +#, fuzzy +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - - . .- - - - - - - - - - - - - -.\n" +": : : :\n" +": list : : :\n" +": +---------+----+----+ : : +---------+----+----+ :\n" +": | Element | 1 | o--+----+-----+--->| Element | 2 | // | :\n" +": +---------+----+----+ : : +---------+----+----+ :\n" +": : : :\n" +": : : :\n" +"'- - - - - - - - - - - - - - ' '- - - - - - - - - - - - - -'\n" "```" msgstr "" -"```rust,editable\n" -"use std::fs::File;\n" -"use std::io::Read;\n" -"\n" -"fn main() {\n" -" let file = File::open(\"diary.txt\");\n" -" match file {\n" -" Ok(mut file) => {\n" -" let mut contents = String::new();\n" -" file.read_to_string(&mut contents);\n" -" println!(\"Dear diary: {contents}\");\n" -" },\n" -" Err(err) => {\n" -" println!(\"The diary could not be opened: {err}\");\n" -" }\n" -" }\n" -"}\n" +"```bob\n" +" 堆疊 堆積\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+----+----+ :\n" +": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" +": | len | 5 | : : +----+----+----+----+----+ :\n" +": | capacity | 5 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - - - - - -'\n" +"`- - - - - - - - - - - - - -'\n" "```" -#: src/error-handling/result.md:27 +#: src/smart-pointers/rc.md msgid "" -"As with `Option`, the successful value sits inside of `Result`, forcing the " -"developer to explicitly extract it. This encourages error checking. In the " -"case where an error should never happen, `unwrap()` or `expect()` can be " -"called, and this is a signal of the developer intent too." +"[`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) is a reference-" +"counted shared pointer. Use this when you need to refer to the same data " +"from multiple places:" msgstr "" -"就跟使用 `Option` 一樣,成功的值會在 Result 內部,這會強制開發人員明確擷取該" -"值,進而有利於檢查錯誤。在應該絕對不會發生錯誤的情況下,可以呼叫 `unwrap()` " -"或 `expect()`,這也是開發人員意圖的訊號。" +"[`Rc`](https://doc.rust-lang.org/std/rc/struct.Rc.html) 是參考計數的共用指" +"標。如要在多個位置參考相同的資料,可以使用這個指標:" -#: src/error-handling/result.md:30 +#: src/smart-pointers/rc.md +msgid "\"a: {a}\"" +msgstr "\"a: {a}\"" + +#: src/smart-pointers/rc.md +msgid "\"b: {b}\"" +msgstr "\"b: {b}\"" + +#: src/smart-pointers/rc.md msgid "" -"`Result` documentation is a recommended read. Not during the course, but it " -"is worth mentioning. It contains a lot of convenience methods and functions " -"that help functional-style programming. " +"See [`Arc`](../concurrency/shared_state/arc.md) and [`Mutex`](https://doc." +"rust-lang.org/std/sync/struct.Mutex.html) if you are in a multi-threaded " +"context." msgstr "" -"建議您參閱 `Result` 說明文件。這不涵蓋在課程內,但值得一提。這份文件收錄許多" -"方便的方法和函式,有助於您進行函式程式設計。" +"如果您處於多執行緒的環境,請參閱 [`Arc`](../concurrency/shared_state/arc.md) " +"和 [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html)。" -#: src/error-handling/try-operator.md:1 -msgid "Propagating Errors with `?`" -msgstr "使用 `?` 傳播錯誤" - -#: src/error-handling/try-operator.md:3 +#: src/smart-pointers/rc.md msgid "" -"The try-operator `?` is used to return errors to the caller. It lets you " -"turn the common" -msgstr "try 運算子 `?` 用於將錯誤傳回呼叫端,讓您將下列常見的程式碼:" +"You can _downgrade_ a shared pointer into a [`Weak`](https://doc.rust-lang." +"org/std/rc/struct.Weak.html) pointer to create cycles that will get dropped." +msgstr "" +"您可以將共用指標「降級」為 [`Weak`](https://doc.rust-lang.org/std/rc/struct." +"Weak.html) 指標,以便建立之後會捨棄的循環。" -#: src/error-handling/try-operator.md:6 +#: src/smart-pointers/rc.md msgid "" -"```rust,ignore\n" -"match some_expression {\n" -" Ok(value) => value,\n" -" Err(err) => return Err(err),\n" -"}\n" +"`Rc`'s count ensures that its contained value is valid for as long as there " +"are references." +msgstr "`Rc` 的計數可確保只要有參考,內含的值就會保持有效。" + +#: src/smart-pointers/rc.md +msgid "`Rc` in Rust is like `std::shared_ptr` in C++." +msgstr "Rust 中的 `Rc` 就像 C++ 中的 `std::shared_ptr` 一樣。" + +#: src/smart-pointers/rc.md +msgid "" +"`Rc::clone` is cheap: it creates a pointer to the same allocation and " +"increases the reference count. Does not make a deep clone and can generally " +"be ignored when looking for performance issues in code." +msgstr "" +"`Rc::clone` 的成本很低:這個做法會建立指向相同配置的指標,並增加參考計數,而" +"不會產生深克隆,尋找程式碼效能問題時通常可以忽略。" + +#: src/smart-pointers/rc.md +msgid "" +"`make_mut` actually clones the inner value if necessary (\"clone-on-write\") " +"and returns a mutable reference." +msgstr "" +"`make_mut` 實際上會在必要時克隆內部值 (「clone-on-write」),並回傳可變動的參" +"考。" + +#: src/smart-pointers/rc.md +msgid "Use `Rc::strong_count` to check the reference count." +msgstr "使用 `Rc::strong_count` 可查看參考計數。" + +#: src/smart-pointers/rc.md +msgid "" +"`Rc::downgrade` gives you a _weakly reference-counted_ object to create " +"cycles that will be dropped properly (likely in combination with `RefCell`)." +msgstr "" +"`Rc::downgrade` 提供的「弱參考計數」物件,建立之後會適當捨棄的循環 (可能會搭" +"配 `RefCell`)。" + +#: src/smart-pointers/trait-objects.md +msgid "" +"Trait objects allow for values of different types, for instance in a " +"collection:" +msgstr "特徵物件可接受不同型別的值,舉例來說,在集合中會是這樣:" + +#: src/smart-pointers/trait-objects.md +msgid "\"Miau!\"" +msgstr "" + +#: src/smart-pointers/trait-objects.md +msgid "\"Hello, who are you? {}\"" +msgstr "\"Hello, who are you? {}\"" + +#: src/smart-pointers/trait-objects.md +msgid "Memory layout after allocating `pets`:" +msgstr "以下是配置 `pets` 後的記憶體配置:" + +#: src/smart-pointers/trait-objects.md +#, fuzzy +msgid "" +"```bob\n" +" Stack Heap\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - " +"- -.\n" +": : : :\n" +": \"pets: Vec\" : : \"data: Cat\" +----+----+----" +"+----+ :\n" +": +-----------+-------+ : : +-------+-------+ | F | i | d | " +"o | :\n" +": | ptr | o---+---+--. : | lives | 9 | +----+----+----" +"+----+ :\n" +": | len | 2 | : | : +-------+-------+ " +"^ :\n" +": | capacity | 2 | : | : ^ " +"| :\n" +": +-----------+-------+ : | : | " +"'-------. :\n" +": : | : | data:" +"\"Dog\"| :\n" +": : | : | +-------+--|-------" +"+ :\n" +"`- - - - - - - - - - - - - -' | : +---|-+-----+ | name | o, 4, 4 " +"| :\n" +" `--+-->| o o | o o-|----->| age | 5 " +"| :\n" +" : +-|---+-|---+ +-------+----------" +"+ :\n" +" : | " +"| :\n" +" `- - -| - - |- - - - - - - - - - - - - - - " +"- -'\n" +" | |\n" +" | | " +"\"Program text\"\n" +" .- - -| - - |- - - - - - - - - - - - - - - " +"- -.\n" +" : | | " +"vtable :\n" +" : | | +----------------------" +"+ :\n" +" : | `----->| \"::" +"talk\" | :\n" +" : | +----------------------" +"+ :\n" +" : | " +"vtable :\n" +" : | +----------------------" +"+ :\n" +" : '----------->| \"::" +"talk\" | :\n" +" : +----------------------" +"+ :\n" +" : :\n" +" '- - - - - - - - - - - - - - - - - - - - - " +"- -'\n" "```" msgstr "" -"```rust,ignore\n" -"match some_expression {\n" -" Ok(value) => value,\n" -" Err(err) => return Err(err),\n" -"}\n" +"```bob\n" +" 堆疊 堆積\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - " +"- -.\n" +": : : :\n" +": pets : : +----+----+----+----" +"+ :\n" +": +-----------+-------+ : : +-----+-----+ .->| F | i | d | o " +"| :\n" +": | ptr | o---+---+-----+-->| o o | o o | | +----+----+----+----" +"+ :\n" +": | len | 2 | : : +-|-|-+-|-|-+ " +"`---------. :\n" +": | capacity | 2 | : : | | | | data " +"| :\n" +": +-----------+-------+ : : | | | | +-------+--|-------" +"+ :\n" +": : : | | | '-->| name | o, 4, 4 " +"| :\n" +": : : | | | | age | 5 " +"| :\n" +"`- - - - - - - - - - - - - -' : | | | +-------+----------" +"+ :\n" +" : | | " +"| :\n" +" : | | | " +"vtable :\n" +" : | | | +----------------------" +"+ :\n" +" : | | '---->| \"::talk\" " +"| :\n" +" : | | +----------------------" +"+ :\n" +" : | " +"| :\n" +" : | | " +"data :\n" +" : | | +-------+-------" +"+ :\n" +" : | '-->| lives | 9 " +"| :\n" +" : | +-------+-------" +"+ :\n" +" : " +"| :\n" +" : | " +"vtable :\n" +" : | +----------------------" +"+ :\n" +" : '---->| \"::talk\" " +"| :\n" +" : +----------------------" +"+ :\n" +" : :\n" +" '- - - - - - - - - - - - - - - - - - - - - " +"- -'\n" "```" -#: src/error-handling/try-operator.md:13 -msgid "into the much simpler" -msgstr "轉換成以下較簡潔的程式碼:" - -#: src/error-handling/try-operator.md:15 +#: src/smart-pointers/trait-objects.md +#, fuzzy msgid "" -"```rust,ignore\n" -"some_expression?\n" -"```" +"Types that implement a given trait may be of different sizes. This makes it " +"impossible to have things like `Vec` in the example above." msgstr "" -"```rust,ignore\n" -"some_expression?\n" -"```" +"如果型別會實作特定特徵,大小可能會不同。因此在上例中就不可能出現 `Vec` " +"這類項目。" -#: src/error-handling/try-operator.md:19 -msgid "We can use this to simplify our error handing code:" -msgstr "我們可以使用這個運算子,簡化錯誤處理程式碼:" - -#: src/error-handling/try-operator.md:21 +#: src/smart-pointers/trait-objects.md msgid "" -"```rust,editable\n" -"use std::fs;\n" -"use std::io::{self, Read};\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let username_file_result = fs::File::open(path);\n" -" let mut username_file = match username_file_result {\n" -" Ok(file) => file,\n" -" Err(err) => return Err(err),\n" -" };\n" -"\n" -" let mut username = String::new();\n" -" match username_file.read_to_string(&mut username) {\n" -" Ok(_) => Ok(username),\n" -" Err(err) => Err(err),\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"alice\").unwrap();\n" -" let username = read_username(\"config.dat\");\n" -" println!(\"username or error: {username:?}\");\n" -"}\n" -"```" +"`dyn Pet` is a way to tell the compiler about a dynamically sized type that " +"implements `Pet`." +msgstr "可透過 `dyn Pet` 這個方法向編譯器告知實作 `Pet` 的動態大小型別。" + +#: src/smart-pointers/trait-objects.md +msgid "" +"In the example, `pets` is allocated on the stack and the vector data is on " +"the heap. The two vector elements are _fat pointers_:" msgstr "" -"```rust,editable\n" -"use std::fs;\n" -"use std::io::{self, Read};\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let username_file_result = fs::File::open(path);\n" -" let mut username_file = match username_file_result {\n" -" Ok(file) => file,\n" -" Err(err) => return Err(err),\n" -" };\n" -"\n" -" let mut username = String::new();\n" -" match username_file.read_to_string(&mut username) {\n" -" Ok(_) => Ok(username),\n" -" Err(err) => Err(err),\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"alice\").unwrap();\n" -" let username = read_username(\"config.dat\");\n" -" println!(\"username or error: {username:?}\");\n" -"}\n" -"```" +"在本例中,`pets` 和向量資料分別在堆疊和堆積上分配。這兩個向量元素都是「虛指" +"標」:" -#: src/error-handling/try-operator.md:50 -#: src/error-handling/converting-error-types-example.md:52 -msgid "The `username` variable can be either `Ok(string)` or `Err(error)`." -msgstr "`username` 變數可以是 `Ok(string)` 或 `Err(error)`。" - -#: src/error-handling/try-operator.md:51 -#: src/error-handling/converting-error-types-example.md:53 +#: src/smart-pointers/trait-objects.md +#, fuzzy msgid "" -"Use the `fs::write` call to test out the different scenarios: no file, empty " -"file, file with username." +"A fat pointer is a double-width pointer. It has two components: a pointer to " +"the actual object and a pointer to the [virtual method table](https://en." +"wikipedia.org/wiki/Virtual_method_table) (vtable) for the `Pet` " +"implementation of that particular object." msgstr "" -"請使用 `fs::write` 呼叫來測試以下不同情況:沒有檔案、空白檔案、含使用者名稱的" -"檔案。" +"在本例中,`pets` 會保留指向物件的「虛指標」__,而物件會實作 `Pet`。虛指標包含" +"兩個元件,指向實際物件的指標,以及指向該特定物件中 `Pet` 實作項目的虛擬方法表" +"格。" -#: src/error-handling/converting-error-types.md:3 +#: src/smart-pointers/trait-objects.md msgid "" -"The effective expansion of `?` is a little more complicated than previously " -"indicated:" -msgstr "比起先前提到的下列程式碼,`?` 的有效擴展稍微更複雜一點:" - -#: src/error-handling/converting-error-types.md:5 -msgid "" -"```rust,ignore\n" -"expression?\n" -"```" +"The data for the `Dog` named Fido is the `name` and `age` fields. The `Cat` " +"has a `lives` field." msgstr "" -"```rust,ignore\n" -"expression?\n" -"```" +"名為 Fido 的 `Dog` 資料是 `name` 和 `age` 欄位。`Cat` 則有 `lives` 欄位。" -#: src/error-handling/converting-error-types.md:9 -msgid "works the same as" -msgstr "運作方式與以下程式碼相同:" +#: src/smart-pointers/trait-objects.md +msgid "Compare these outputs in the above example:" +msgstr "比較上述範例的輸出內容:" -#: src/error-handling/converting-error-types.md:11 +#: src/smart-pointers/exercise.md msgid "" -"```rust,ignore\n" -"match expression {\n" -" Ok(value) => value,\n" -" Err(err) => return Err(From::from(err)),\n" -"}\n" -"```" +"A binary tree is a tree-type data structure where every node has two " +"children (left and right). We will create a tree where each node stores a " +"value. For a given node N, all nodes in a N's left subtree contain smaller " +"values, and all nodes in N's right subtree will contain larger values." msgstr "" -"```rust,ignore\n" -"match expression {\n" -" Ok(value) => value,\n" -" Err(err) => return Err(From::from(err)),\n" -"}\n" -"```" +"二元樹是一種樹狀資料結構,其中每個節點都有左右兩個子節點。我們會建立每個節點" +"都儲存一個值的樹狀結構。以指定節點 N 來說,N 左側子樹狀結構中的所有節點都包含" +"較小的值,而 N 右側子樹狀結構中的所有節點都含有較大的值。" -#: src/error-handling/converting-error-types.md:18 +#: src/smart-pointers/exercise.md +msgid "Implement the following types, so that the given tests pass." +msgstr "請實作以下型別,讓指定的測試通過。" + +#: src/smart-pointers/exercise.md msgid "" -"The `From::from` call here means we attempt to convert the error type to the " -"type returned by the function:" +"Extra Credit: implement an iterator over a binary tree that returns the " +"values in order." +msgstr "加分題:在二元數上實作疊代器,依序傳回值。" + +#: src/smart-pointers/exercise.md src/smart-pointers/solution.md +msgid "/// A node in the binary tree.\n" +msgstr "/// A node in the binary tree.\n" + +#: src/smart-pointers/exercise.md src/smart-pointers/solution.md +msgid "/// A possibly-empty subtree.\n" +msgstr "/// A possibly-empty subtree.\n" + +#: src/smart-pointers/exercise.md src/smart-pointers/solution.md +msgid "" +"/// A container storing a set of values, using a binary tree.\n" +"///\n" +"/// If the same value is added multiple times, it is only stored once.\n" msgstr "" -"這裡的 `From::from` 呼叫意味著,我們嘗試將錯誤型別轉換成函式回傳的型別:" +"/// A container storing a set of values, using a binary tree.\n" +"///\n" +"/// If the same value is added multiple times, it is only stored once.\n" -#: src/error-handling/converting-error-types-example.md:3 +#: src/smart-pointers/exercise.md +msgid "// Implement `new`, `insert`, `len`, and `has`.\n" +msgstr "// Implement `new`, `insert`, `len`, and `has`.\n" + +#: src/smart-pointers/exercise.md src/smart-pointers/solution.md +msgid "// not a unique item\n" +msgstr "// not a unique item\n" + +#: src/smart-pointers/solution.md src/android/testing/googletest.md +msgid "\"bar\"" +msgstr "\"bar\"" + +#: src/welcome-day-3-afternoon.md +msgid "[Borrowing](./borrowing.md) (50 minutes)" +msgstr "[借用](./borrowing.md) (50 分鐘)" + +#: src/welcome-day-3-afternoon.md msgid "" -"```rust,editable\n" -"use std::error::Error;\n" -"use std::fmt::{self, Display, Formatter};\n" -"use std::fs::{self, File};\n" -"use std::io::{self, Read};\n" -"\n" -"#[derive(Debug)]\n" -"enum ReadUsernameError {\n" -" IoError(io::Error),\n" -" EmptyUsername(String),\n" -"}\n" -"\n" -"impl Error for ReadUsernameError {}\n" -"\n" -"impl Display for ReadUsernameError {\n" -" fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n" -" match self {\n" -" Self::IoError(e) => write!(f, \"IO error: {e}\"),\n" -" Self::EmptyUsername(filename) => write!(f, \"Found no username " -"in {filename}\"),\n" -" }\n" -" }\n" -"}\n" -"\n" -"impl From for ReadUsernameError {\n" -" fn from(err: io::Error) -> ReadUsernameError {\n" -" ReadUsernameError::IoError(err)\n" -" }\n" -"}\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" let username = read_username(\"config.dat\");\n" -" println!(\"username or error: {username:?}\");\n" -"}\n" -"```" +"[Slices and Lifetimes](./slices-and-lifetimes.md) (1 hour and 10 minutes)" +msgstr "[切片和生命週期](./slices-and-lifetimes.md) (1 小時 10 分鐘)" + +#: src/borrowing.md +msgid "[Borrowing a Value](./borrowing/shared.md) (10 minutes)" +msgstr "[如何借用值](./borrowing/shared.md) (10 分鐘)" + +#: src/borrowing.md +msgid "[Borrow Checking](./borrowing/borrowck.md) (10 minutes)" +msgstr "[借用檢查](./borrowing/borrowck.md) (10 分鐘)" + +#: src/borrowing.md +msgid "[Interior Mutability](./borrowing/interior-mutability.md) (10 minutes)" +msgstr "[內部可變動性](./borrowing/interior-mutability.md) (10 分鐘)" + +#: src/borrowing.md +msgid "[Exercise: Health Statistics](./borrowing/exercise.md) (20 minutes)" +msgstr "[練習:健康統計資料](./borrowing/exercise.md) (20 分鐘)" + +#: src/borrowing/shared.md +#, fuzzy +msgid "" +"As we saw before, instead of transferring ownership when calling a function, " +"you can let a function _borrow_ the value:" +msgstr "您可以不必在呼叫函式時轉移所有權,而是讓函式「借用」值:" + +#: src/borrowing/shared.md +msgid "The `add` function _borrows_ two points and returns a new point." +msgstr "`add` 函式會「借用」兩個點,並傳回新的點。" + +#: src/borrowing/shared.md +msgid "The caller retains ownership of the inputs." +msgstr "呼叫端會保留輸入內容的所有權。" + +#: src/borrowing/shared.md +msgid "" +"This slide is a review of the material on references from day 1, expanding " +"slightly to include function arguments and return values." msgstr "" -"```rust,editable\n" -"use std::error::Error;\n" -"use std::fmt::{self, Display, Formatter};\n" -"use std::fs::{self, File};\n" -"use std::io::{self, Read};\n" -"\n" -"#[derive(Debug)]\n" -"enum ReadUsernameError {\n" -" IoError(io::Error),\n" -" EmptyUsername(String),\n" -"}\n" -"\n" -"impl Error for ReadUsernameError {}\n" -"\n" -"impl Display for ReadUsernameError {\n" -" fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n" -" match self {\n" -" Self::IoError(e) => write!(f, \"IO error: {e}\"),\n" -" Self::EmptyUsername(filename) => write!(f, \"Found no username " -"in {filename}\"),\n" -" }\n" -" }\n" -"}\n" -"\n" -"impl From for ReadUsernameError {\n" -" fn from(err: io::Error) -> ReadUsernameError {\n" -" ReadUsernameError::IoError(err)\n" -" }\n" -"}\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" let username = read_username(\"config.dat\");\n" -" println!(\"username or error: {username:?}\");\n" -"}\n" -"```" +"這張投影片會複習第 1 天講解過的參照,並略微延伸討論何謂函式引數和回傳值。" -#: src/error-handling/converting-error-types-example.md:55 +#: src/borrowing/shared.md +msgid "Notes on stack returns:" +msgstr "有關堆疊回傳的注意事項:" + +#: src/borrowing/shared.md +#, fuzzy msgid "" -"It is good practice for all error types to implement `std::error::Error`, " -"which requires `Debug` and `Display`. It's generally helpful for them to " -"implement `Clone` and `Eq` too where possible, to make life easier for tests " -"and consumers of your library. In this case we can't easily do so, because " -"`io::Error` doesn't implement them." +"Demonstrate that the return from `add` is cheap because the compiler can " +"eliminate the copy operation. Change the above code to print stack addresses " +"and run it on the [Playground](https://play.rust-lang.org/?" +"version=stable&mode=release&edition=2021&gist=0cb13be1c05d7e3446686ad9947c4671) " +"or look at the assembly in [Godbolt](https://rust.godbolt.org/). In the " +"\"DEBUG\" optimization level, the addresses should change, while they stay " +"the same when changing to the \"RELEASE\" setting:" msgstr "" +"示範因為編譯器可刪除複製操作,所以 `add` 回傳的成本較低。變更上述程式碼來顯示" +"堆疊位址,並在 [Playground](https://play.rust-lang.org/) 上執行。在「DEBUG」" +"最佳化等級中,位址應變更,但在變更為「RELEASE」設定時,位址應維持不變:" -#: src/error-handling/deriving-error-enums.md:3 +#: src/borrowing/shared.md +msgid "The Rust compiler can do return value optimization (RVO)." +msgstr "Rust 編譯器可以執行回傳值最佳化 (RVO)。" + +#: src/borrowing/shared.md +#, fuzzy msgid "" -"The [thiserror](https://docs.rs/thiserror/) crate is a popular way to create " -"an error enum like we did on the previous page:" +"In C++, copy elision has to be defined in the language specification because " +"constructors can have side effects. In Rust, this is not an issue at all. If " +"RVO did not happen, Rust will always perform a simple and efficient `memcpy` " +"copy." msgstr "" -"[thiserror](https://docs.rs/thiserror/) crate 很常用來建立錯誤列舉,我們在上" -"一頁就曾這麼做:" +"在 C++ 中,複製省略必須定義在語言規格內,因為建構函式可能有連帶效果。在 Rust " +"中,這完全不是問題。如未發生 RVO,Rust 一律會執行簡單有效的 `memcpy` 複製作" +"業。" -#: src/error-handling/deriving-error-enums.md:6 +#: src/borrowing/borrowck.md +#, fuzzy msgid "" -"```rust,editable,compile_fail\n" -"use std::{fs, io};\n" -"use std::io::Read;\n" -"use thiserror::Error;\n" -"\n" -"#[derive(Debug, Error)]\n" -"enum ReadUsernameError {\n" -" #[error(\"Could not read: {0}\")]\n" -" IoError(#[from] io::Error),\n" -" #[error(\"Found no username in {0}\")]\n" -" EmptyUsername(String),\n" -"}\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" fs::File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err}\"),\n" -" }\n" -"}\n" -"```" +"Rust's _borrow checker_ puts constraints on the ways you can borrow values. " +"For a given value, at any time:" +msgstr "Rust 會限制借用值的方式:" + +#: src/borrowing/borrowck.md +#, fuzzy +msgid "You can have one or more shared references to the value, _or_" +msgstr "隨時擁有一或多個 `&T` 值,「或是」" + +#: src/borrowing/borrowck.md +#, fuzzy +msgid "You can have exactly one exclusive reference to the value." +msgstr "只擁有一個 `&mut T` 值。" + +#: src/borrowing/borrowck.md +msgid "" +"Note that the requirement is that conflicting references not _exist_ at the " +"same point. It does not matter where the reference is dereferenced." msgstr "" -"```rust,editable,compile_fail\n" -"use std::{fs, io};\n" -"use std::io::Read;\n" -"use thiserror::Error;\n" -"\n" -"#[derive(Debug, Error)]\n" -"enum ReadUsernameError {\n" -" #[error(\"Could not read: {0}\")]\n" -" IoError(#[from] io::Error),\n" -" #[error(\"Found no username in {0}\")]\n" -" EmptyUsername(String),\n" -"}\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" fs::File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(ReadUsernameError::EmptyUsername(String::from(path)));\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err}\"),\n" -" }\n" -"}\n" -"```" +"請注意,這裡的規定是同一點上不得「存在」衝突的參照,在何處解除參照並不重要。" -#: src/error-handling/deriving-error-enums.md:39 +#: src/borrowing/borrowck.md msgid "" -"`thiserror`'s derive macro automatically implements `std::error::Error`, and " -"optionally `Display` (if the `#[error(...)]` attributes are provided) and " -"`From` (if the `#[from]` attribute is added). It also works for structs." +"The above code does not compile because `a` is borrowed as mutable (through " +"`c`) and as immutable (through `b`) at the same time." msgstr "" -"`thiserror` 的衍生巨集會自動實作 `std::error::Error`,並視情況實作 `Display` " -"(如果提供了 `#[error(...)]` 屬性的話) 和 `From` (如果新增了 `#[from]` 屬性的" -"話)。上述原則也適用於結構體。" +"上述程式碼不會編譯,因為系統會同時透過 `c` 和 `b`,以可變動項和不可變動項的格" +"式借用 `a`。" -#: src/error-handling/deriving-error-enums.md:43 -msgid "It doesn't affect your public API, which makes it good for libraries." -msgstr "這個不會影響你的公用API,因此這對程式庫很好。" - -#: src/error-handling/dynamic-errors.md:3 +#: src/borrowing/borrowck.md msgid "" -"Sometimes we want to allow any type of error to be returned without writing " -"our own enum covering all the different possibilities. `std::error::Error` " -"makes this easy." +"Move the `println!` statement for `b` before the scope that introduces `c` " +"to make the code compile." +msgstr "請將 `b` 的 `println!` 陳述式移到導入 `c` 的範圍前,即可編譯程式碼。" + +#: src/borrowing/borrowck.md +msgid "" +"After that change, the compiler realizes that `b` is only ever used before " +"the new mutable borrow of `a` through `c`. This is a feature of the borrow " +"checker called \"non-lexical lifetimes\"." msgstr "" -"我們有時會想允許傳回任何型別的錯誤,而不是自行編寫涵蓋所有不同可能性的列舉。" -"`std::error::Error` 可讓這項工作更輕鬆。" +"經過該變更後,編譯器會發現系統使用 `b` 的時間,只會在新可變動項透過 `c` 借用 " +"`a` 之前。這是借用檢查器中的功能,稱為「非詞彙生命週期」(non-lexical " +"lifetimes)。" -#: src/error-handling/dynamic-errors.md:6 +#: src/borrowing/borrowck.md msgid "" -"```rust,editable,compile_fail\n" -"use std::fs::{self, File};\n" -"use std::io::Read;\n" -"use thiserror::Error;\n" -"use std::error::Error;\n" -"\n" -"#[derive(Clone, Debug, Eq, Error, PartialEq)]\n" -"#[error(\"Found no username in {0}\")]\n" -"struct EmptyUsernameError(String);\n" -"\n" -"fn read_username(path: &str) -> Result> {\n" -" let mut username = String::with_capacity(100);\n" -" File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(EmptyUsernameError(String::from(path)).into());\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err}\"),\n" -" }\n" -"}\n" -"```" +"The exclusive reference constraint is quite strong. Rust uses it to ensure " +"that data races do not occur. Rust also _relies_ on this constraint to " +"optimize code. For example, a value behind a shared reference can be safely " +"cached in a register for the lifetime of that reference." msgstr "" -"```rust,editable,compile_fail\n" -"use std::fs::{self, File};\n" -"use std::io::Read;\n" -"use thiserror::Error;\n" -"use std::error::Error;\n" -"\n" -"#[derive(Clone, Debug, Eq, Error, PartialEq)]\n" -"#[error(\"Found no username in {0}\")]\n" -"struct EmptyUsernameError(String);\n" -"\n" -"fn read_username(path: &str) -> Result> {\n" -" let mut username = String::with_capacity(100);\n" -" File::open(path)?.read_to_string(&mut username)?;\n" -" if username.is_empty() {\n" -" return Err(EmptyUsernameError(String::from(path)).into());\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err}\"),\n" -" }\n" -"}\n" -"```" +"專屬參照的約束力很強。Rust 會利用這類參照,確保資料競爭的情形不會發生;此外," +"也會「透過」這項約束,將程式碼最佳化。舉例來說,共用參照背後的值可以在該參照" +"的生命週期內,安全地快取到暫存器中。" -#: src/error-handling/dynamic-errors.md:36 +#: src/borrowing/borrowck.md msgid "" -"This saves on code, but gives up the ability to cleanly handle different " -"error cases differently in the program. As such it's generally not a good " -"idea to use `Box` in the public API of a library, but it can be a " -"good option in a program where you just want to display the error message " -"somewhere." +"The borrow checker is designed to accommodate many common patterns, such as " +"taking exclusive references to different fields in a struct at the same " +"time. But, there are some situations where it doesn't quite \"get it\" and " +"this often results in \"fighting with the borrow checker.\"" msgstr "" -"這可少用一些程式碼,但犧牲掉的是無法在程式中以不同方式乾淨地處理各種錯誤情" -"況。因此,在程式庫的公用 API 中使用 `Box`,通常不是一個理想方式," -"但如果您只想在程式中的某處顯示錯誤訊息,它可能是不錯的選擇。" +"借用檢查器在設計上考量了許多常見模式,例如同時對結構體中的不同欄位進行專屬參" +"照。但檢查器也可能無法完全「理解」某些的情況,這通常會導致「與借用檢查器衝" +"突」。" -#: src/error-handling/error-contexts.md:3 +#: src/borrowing/interior-mutability.md msgid "" -"The widely used [anyhow](https://docs.rs/anyhow/) crate can help you add " -"contextual information to your errors and allows you to have fewer custom " -"error types:" +"In some situations, it's necessary to modify data behind a shared (read-" +"only) reference. For example, a shared data structure might have an internal " +"cache, and wish to update that cache from read-only methods." msgstr "" -"透過廣泛使用的 [anyhow](https://docs.rs/anyhow/) crate,您可以為錯誤添加背景" -"資訊,並減少自訂錯誤型別的數量:" +"在某些情況下,您必須修改共用 (唯讀) 參照背後的資料:比方說,共用的資料結構可" +"能含有內部快取,並想透過唯讀方法更新該快取。" -#: src/error-handling/error-contexts.md:7 +#: src/borrowing/interior-mutability.md msgid "" -"```rust,editable,compile_fail\n" -"use std::{fs, io};\n" -"use std::io::Read;\n" -"use anyhow::{Context, Result, bail};\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" fs::File::open(path)\n" -" .with_context(|| format!(\"Failed to open {path}\"))?\n" -" .read_to_string(&mut username)\n" -" .context(\"Failed to read\")?;\n" -" if username.is_empty() {\n" -" bail!(\"Found no username in {path}\");\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err:?}\"),\n" -" }\n" -"}\n" -"```" +"The \"interior mutability\" pattern allows exclusive (mutable) access behind " +"a shared reference. The standard library provides several ways to do this, " +"all while still ensuring safety, typically by performing a runtime check." msgstr "" -"```rust,editable,compile_fail\n" -"use std::{fs, io};\n" -"use std::io::Read;\n" -"use anyhow::{Context, Result, bail};\n" -"\n" -"fn read_username(path: &str) -> Result {\n" -" let mut username = String::with_capacity(100);\n" -" fs::File::open(path)\n" -" .with_context(|| format!(\"Failed to open {path}\"))?\n" -" .read_to_string(&mut username)\n" -" .context(\"Failed to read\")?;\n" -" if username.is_empty() {\n" -" bail!(\"Found no username in {path}\");\n" -" }\n" -" Ok(username)\n" -"}\n" -"\n" -"fn main() {\n" -" //fs::write(\"config.dat\", \"\").unwrap();\n" -" match read_username(\"config.dat\") {\n" -" Ok(username) => println!(\"Username: {username}\"),\n" -" Err(err) => println!(\"Error: {err:?}\"),\n" -" }\n" -"}\n" -"```" +"「內部可變動性」模式可以在共用參照背後提供專屬 (可變動的) 存取權。標準程式庫" +"支援以多種方式執行此操作,同時仍可確保安全,做法通常是執行執行階段檢查。" -#: src/error-handling/error-contexts.md:35 -msgid "`anyhow::Result` is a type alias for `Result`." -msgstr "`anyhow::Result` 是 `Result` 的型別別名。" +#: src/borrowing/interior-mutability.md +#, fuzzy +msgid "`RefCell`" +msgstr "`RefCell`" -#: src/error-handling/error-contexts.md:36 +#: src/borrowing/interior-mutability.md +msgid "\"graph: {root:#?}\"" +msgstr "\"graph: {root:#?}\"" + +#: src/borrowing/interior-mutability.md +msgid "\"graph sum: {}\"" +msgstr "\"graph sum: {}\"" + +#: src/borrowing/interior-mutability.md +msgid "`Cell`" +msgstr "`Cell`" + +#: src/borrowing/interior-mutability.md msgid "" -"`anyhow::Error` is essentially a wrapper around `Box`. As such " -"it's again generally not a good choice for the public API of a library, but " -"is widely used in applications." +"`Cell` wraps a value and allows getting or setting the value, even with a " +"shared reference to the `Cell`. However, it does not allow any references to " +"the value. Since there are no references, borrowing rules cannot be broken." msgstr "" -"`anyhow::Error` 基本上是 `Box` 周遭的包裝函式。因此,通常也是不建" -"議程式庫的公用 API 使用,但可在應用程式中廣泛使用。" +"`Cell` 會納入值,並允許取得或設定該值,即使具有對 `Cell` 的共用參照也一樣。但" +"是,它不允許對該值進行任何參照。由於沒有參照,因此借用規則不得違反。" -#: src/error-handling/error-contexts.md:38 +#: src/borrowing/interior-mutability.md msgid "" -"Actual error type inside of it can be extracted for examination if necessary." -msgstr "必要時,可以擷取其中的實際錯誤類型進行檢查。" - -#: src/error-handling/error-contexts.md:39 -msgid "" -"Functionality provided by `anyhow::Result` may be familiar to Go " -"developers, as it provides similar usage patterns and ergonomics to `(T, " -"error)` from Go." +"The main thing to take away from this slide is that Rust provides _safe_ " +"ways to modify data behind a shared reference. There are a variety of ways " +"to ensure that safety, and `RefCell` and `Cell` are two of them." msgstr "" -"Go 開發人員可能會覺得 `anyhow::Result` 提供的功能似曾相識,因為該功能提供" -"了與 Go 中的 `(T, error)` 類似的使用模式和人體工學。" +"這張投影片的重點是 Rust 提供「安全的」方法,可讓您修改共用參照背後的資料。要" +"確保安全性有許多方式,而 `RefCell` 和 `Cell` 是其中兩種方法。" -#: src/testing.md:3 +#: src/borrowing/interior-mutability.md +msgid "" +"`RefCell` enforces Rust's usual borrowing rules (either multiple shared " +"references or a single exclusive reference) with a runtime check. In this " +"case, all borrows are very short and never overlap, so the checks always " +"succeed." +msgstr "" +"`RefCell` 會透過執行階段檢查,強制使用 Rust 的一般借用規則 (多個共用參照或單" +"一專屬參照)。在本例中,所有借用都非常短暫且永遠不會重疊,因此檢查一律會成功。" + +#: src/borrowing/interior-mutability.md +msgid "" +"`Rc` only allows shared (read-only) access to its contents, since its " +"purpose is to allow (and count) many references. But we want to modify the " +"value, so we need interior mutability." +msgstr "" +"`Rc` 只允許對自身內容的共用 (唯讀) 存取行為,因為允許 (並計算) 多個參照才是它" +"的用途。但是,由於我們要修改這個值,因此內部可變動性不可或缺。" + +#: src/borrowing/interior-mutability.md +msgid "" +"`Cell` is a simpler means to ensure safety: it has a `set` method that takes " +"`&self`. This needs no runtime check, but requires moving values, which can " +"have its own cost." +msgstr "" +"如要確保安全,`Cell` 是較簡單的做法,因為其中的 `set` 方法可接受 `&self`。這" +"無需動用執行階段檢查,但需要移動值,因此可能有其相應成本。" + +#: src/borrowing/interior-mutability.md +#, fuzzy +msgid "" +"Demonstrate that reference loops can be created by adding `root` to `subtree." +"children`." +msgstr "" +"示範可以將 `root` 新增至 `subtree.children` (請勿嘗試輸出!) 來建立參照迴圈。" + +#: src/borrowing/interior-mutability.md +msgid "" +"To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments " +"`self.value` and calls the same method on its children. This will panic in " +"the presence of the reference loop, with `thread 'main' panicked at 'already " +"borrowed: BorrowMutError'`." +msgstr "" +"如要演示執行階段發生的恐慌情形,請新增 `fn inc(&mut self)`,這可讓 `self." +"value` 遞增,並在其子項呼叫相同的方法。在有參照迴圈的情況下,這會引發恐慌,其" +"中的 `thread 'main' 會因 'already borrowed: BorrowMutError'` 而恐慌。" + +#: src/borrowing/exercise.md +msgid "" +"You're working on implementing a health-monitoring system. As part of that, " +"you need to keep track of users' health statistics." +msgstr "您正在實作健康監控系統,因此須追蹤使用者的健康統計資料。" + +#: src/borrowing/exercise.md +#, fuzzy +msgid "" +"You'll start with a stubbed function in an `impl` block as well as a `User` " +"struct definition. Your goal is to implement the stubbed out method on the " +"`User` `struct` defined in the `impl` block." +msgstr "" +"您將從 `impl` 區塊中的部分虛設函式,以及 `User` 結構體定義著手,目標是在 " +"`impl` 區塊中定義的 `User` `struct` 上導入虛設常式方法。" + +#: src/borrowing/exercise.md +#, fuzzy +msgid "" +"Copy the code below to and fill in the missing " +"method:" +msgstr "請將以下程式碼複製到 ,並填入缺少的方法:" + +#: src/borrowing/exercise.md +msgid "" +"\"Update a user's statistics based on measurements from a visit to the " +"doctor\"" +msgstr "" +"\"Update a user's statistics based on measurements from a visit to the " +"doctor\"" + +#: src/borrowing/exercise.md src/borrowing/solution.md +#: src/android/build-rules/library.md +#: src/android/aidl/example-service/client.md +msgid "\"Bob\"" +msgstr "\"Bob\"" + +#: src/borrowing/exercise.md src/borrowing/solution.md +msgid "\"I'm {} and my age is {}\"" +msgstr "\"I'm {} and my age is {}\"" + +#: src/slices-and-lifetimes.md +msgid "[Slices: &\\[T\\]](./slices-and-lifetimes/slices.md) (10 minutes)" +msgstr "[切片: &\\[T\\]](./slices-and-lifetimes/slices.md) (10 分鐘)" + +#: src/slices-and-lifetimes.md +msgid "[String References](./slices-and-lifetimes/str.md) (10 minutes)" +msgstr "[字串參照](./slices-and-lifetimes/str.md) (10 分鐘)" + +#: src/slices-and-lifetimes.md +msgid "" +"[Lifetime Annotations](./slices-and-lifetimes/lifetime-annotations.md) (10 " +"minutes)" +msgstr "" +"[生命週期註解](./slices-and-lifetimes/lifetime-annotations.md) (10 分鐘)" + +#: src/slices-and-lifetimes.md +msgid "" +"[Lifetime Elision](./slices-and-lifetimes/lifetime-elision.md) (5 minutes)" +msgstr "[生命週期省略](./slices-and-lifetimes/lifetime-elision.md) (5 分鐘)" + +#: src/slices-and-lifetimes.md +msgid "" +"[Struct Lifetimes](./slices-and-lifetimes/struct-lifetimes.md) (5 minutes)" +msgstr "[結構體生命週期](./slices-and-lifetimes/struct-lifetimes.md) (5 分鐘)" + +#: src/slices-and-lifetimes.md +msgid "" +"[Exercise: Protobuf Parsing](./slices-and-lifetimes/exercise.md) (30 minutes)" +msgstr "[練習:Protobuf 剖析](./slices-and-lifetimes/exercise.md) (30 分鐘)" + +#: src/slices-and-lifetimes.md +msgid "This segment should take about 1 hour and 10 minutes" +msgstr "講解這個主題大約需要 1 小時 10 分鐘" + +#: src/slices-and-lifetimes/slices.md +msgid "Slices" +msgstr "切片" + +#: src/slices-and-lifetimes/slices.md +msgid "A slice gives you a view into a larger collection:" +msgstr "切片能讓您查看更大的集合:" + +#: src/slices-and-lifetimes/slices.md +msgid "Slices borrow data from the sliced type." +msgstr "切片會從切片型別借用資料。" + +#: src/slices-and-lifetimes/slices.md +msgid "Question: What happens if you modify `a[3]` right before printing `s`?" +msgstr "問題:如果在輸出 `s` 前修改 `a[3]`,會有什麼影響?" + +#: src/slices-and-lifetimes/slices.md +msgid "" +"We create a slice by borrowing `a` and specifying the starting and ending " +"indexes in brackets." +msgstr "我們會建立一個切片,方法是先借用 `a`,然後在括號中指定起始和結束索引。" + +#: src/slices-and-lifetimes/slices.md +msgid "" +"If the slice starts at index 0, Rust’s range syntax allows us to drop the " +"starting index, meaning that `&a[0..a.len()]` and `&a[..a.len()]` are " +"identical." +msgstr "" +"如果切片從索引 0 開始,Rust 的範圍語法可允許我們捨棄起始索引,也就是說," +"`&a[0..a.len()]` 和 `&a[..a.len()]` 意思相同。" + +#: src/slices-and-lifetimes/slices.md +msgid "" +"The same is true for the last index, so `&a[2..a.len()]` and `&a[2..]` are " +"identical." +msgstr "" +"同理,最後一個索引也是如此,因此 `&a[2..a.len()]` 和 `&a[2..]` 意思相同。" + +#: src/slices-and-lifetimes/slices.md +msgid "" +"To easily create a slice of the full array, we can therefore use `&a[..]`." +msgstr "因此,為了輕鬆建立完整陣列的切片,我們可以使用 `&a[..]`。" + +#: src/slices-and-lifetimes/slices.md +msgid "" +"`s` is a reference to a slice of `i32`s. Notice that the type of `s` " +"(`&[i32]`) no longer mentions the array length. This allows us to perform " +"computation on slices of different sizes." +msgstr "" +"`s` 是對 `i32`s 切片的參照。請注意,`s` (`&[i32]`) 的型別不再提及陣列長度,這" +"有利於我們對不同大小的切片執行運算。" + +#: src/slices-and-lifetimes/slices.md +#, fuzzy +msgid "" +"Slices always borrow from another object. In this example, `a` has to remain " +"'alive' (in scope) for at least as long as our slice." +msgstr "" +"切片一律會從其他物件借用。在本例中,`a` 必須持續「運作」(在範圍內),時間至少" +"要和切片一樣長。" + +#: src/slices-and-lifetimes/slices.md +#, fuzzy +msgid "" +"The question about modifying `a[3]` can spark an interesting discussion, but " +"the answer is that for memory safety reasons you cannot do it through `a` at " +"this point in the execution, but you can read the data from both `a` and `s` " +"safely. It works before you created the slice, and again after the " +"`println`, when the slice is no longer used." +msgstr "" +"有關修改 `a[3]` 的問題可能引發有趣的討論,但正解是,基於記憶體安全因素,您無" +"法在執行作業的這個時間點,透過 `a` 修改 `a[3]`,但可以放心從 `a` 和 `s` 讀取" +"資料。此項目會在您建立切片前運作,並在 `println` 之後,也就是切片不再使用時再" +"次運作。更多細節會在借用檢查器的章節說明。" + +#: src/slices-and-lifetimes/str.md +msgid "" +"We can now understand the two string types in Rust: `&str` is almost like " +"`&[char]`, but with its data stored in a variable-length encoding (UTF-8)." +msgstr "" +"我們現在可以瞭解 Rust 中有兩種字串型別,`&str` 幾近於 `&[char]`,但其資料是以" +"可變長度編碼 (UTF-8) 儲存。" + +#: src/slices-and-lifetimes/str.md +msgid "\"s1: {s1}\"" +msgstr "\"s1: {s1}\"" + +#: src/slices-and-lifetimes/str.md +msgid "\"Hello \"" +msgstr "\"Hello \"" + +#: src/slices-and-lifetimes/str.md +msgid "\"s3: {s3}\"" +msgstr "\"s3: {s3}\"" + +#: src/slices-and-lifetimes/str.md +msgid "Rust terminology:" +msgstr "以 Rust 術語來說會是這樣:" + +#: src/slices-and-lifetimes/str.md +msgid "`&str` an immutable reference to a string slice." +msgstr "`&str` 是對字串切片的不可變參照。" + +#: src/slices-and-lifetimes/str.md +msgid "`String` a mutable string buffer." +msgstr "`String` 是可變動的字串緩衝區。" + +#: src/slices-and-lifetimes/str.md +#, fuzzy +msgid "" +"`&str` introduces a string slice, which is an immutable reference to UTF-8 " +"encoded string data stored in a block of memory. String literals " +"(`”Hello”`), are stored in the program’s binary." +msgstr "" +"`&str` 可引進字串切片,這是對 UTF-8 編碼字串的不可變參照;該編碼字串儲存在記" +"憶體區塊中,字串常值 (`”Hello”`) 則儲存在程式的二進位檔中。" + +#: src/slices-and-lifetimes/str.md +msgid "" +"Rust’s `String` type is a wrapper around a vector of bytes. As with a " +"`Vec`, it is owned." +msgstr "" +"Rust 的 `String` 型別是位元組向量的包裝函式。就像使用 `Vec` 一樣,該型別有" +"專屬的擁有者。" + +#: src/slices-and-lifetimes/str.md +#, fuzzy +msgid "" +"As with many other types `String::from()` creates a string from a string " +"literal; `String::new()` creates a new empty string, to which string data " +"can be added using the `push()` and `push_str()` methods." +msgstr "" +"就像使用其他許多型別一樣,`String::from()` 會透過字串常值建立字串;`String::" +"new()` 則建立新的空白字串,您可以使用 `push()` 和 `push_str()` 方法將字串資料" +"加到該字串。" + +#: src/slices-and-lifetimes/str.md +#, fuzzy +msgid "" +"The `format!()` macro is a convenient way to generate an owned string from " +"dynamic values. It accepts the same format specification as `println!()`." +msgstr "" +"如要從動態值產生自有字串,使用 `format!()` 巨集是便捷的方法。該巨集接受與 " +"`println!()` 相同的格式規格。" + +#: src/slices-and-lifetimes/str.md +msgid "" +"You can borrow `&str` slices from `String` via `&` and optionally range " +"selection. If you select a byte range that is not aligned to character " +"boundaries, the expression will panic. The `chars` iterator iterates over " +"characters and is preferred over trying to get character boundaries right." +msgstr "" +"您可以透過 `&str` 和可選的範圍選項,從 `String` 借用 `&str` 切片。如果所選位" +"元組範圍未與字元邊界對齊,運算式會發生恐慌。比起嘗試設定正確的字元邊界,建議" +"優先使用會對字元進行疊代的 `chars` 疊代器。" + +#: src/slices-and-lifetimes/str.md +#, fuzzy +msgid "" +"For C++ programmers: think of `&str` as `std::string_view` from C++, but the " +"one that always points to a valid string in memory. Rust `String` is a rough " +"equivalent of `std::string` from C++ (main difference: it can only contain " +"UTF-8 encoded bytes and will never use a small-string optimization)." +msgstr "" +"C++ 程式設計師請注意:您可以將 `&str` 想成 C++ 的 `const char*`,但這個 " +"`&str` 將一律指向記憶體中的有效字串。Rust 的 `String` 大致等同於 C++ 的 " +"`std::string`,主要差別是前者只能包含 UTF-8 編碼的位元組,且絕不會進行小字串" +"最佳化。" + +#: src/slices-and-lifetimes/str.md +#, fuzzy +msgid "Byte strings literals allow you to create a `&[u8]` value directly:" +msgstr "位元組字串可讓您直接建立 `&[u8]` 值:" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "" +"A reference has a _lifetime_, which must not \"outlive\" the value it refers " +"to. This is verified by the borrow checker." +msgstr "參照的「生命週期」不得「超過」其所參照的值。此由借用檢查器負責驗證。" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "" +"The lifetime can be implicit - this is what we have seen so far. Lifetimes " +"can also be explicit: `&'a Point`, `&'document str`. Lifetimes start with " +"`'` and `'a` is a typical default name. Read `&'a Point` as \"a borrowed " +"`Point` which is valid for at least the lifetime `a`\"." +msgstr "" +"按照我們目前所見,生命週期可以隱晦表示。不過,`&'a Point`、`&'document str` " +"也可以明確表示生命週期。生命週期的開頭為 `'`,一般預設名稱為 `'a``。請將 " +"`&'a Point` 讀做「至少對生命週期 `a` 有效的借用 `Point`」。" + +#: src/slices-and-lifetimes/lifetime-annotations.md +#, fuzzy +msgid "" +"Lifetimes are always inferred by the compiler: you cannot assign a lifetime " +"yourself. Explicit lifetime annotations create constraints where there is " +"ambiguity; the compiler verifies that there is a valid solution." +msgstr "生命週期註解會建立限制;編譯器會驗證是否有有效的解決方案。" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "" +"Lifetimes become more complicated when considering passing values to and " +"returning values from functions." +msgstr "在考慮與函式間傳遞值時,生命週期會變得比較複雜。" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "// What is the lifetime of p3?\n" +msgstr "// What is the lifetime of p3?\n" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "\"p3: {p3:?}\"" +msgstr "\"p3: {p3:?}\"" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "" +"In this example, the compiler does not know what lifetime to infer for `p3`. " +"Looking inside the function body shows that it can only safely assume that " +"`p3`'s lifetime is the shorter of `p1` and `p2`. But just like types, Rust " +"requires explicit annotations of lifetimes on function arguments and return " +"values." +msgstr "" +"在本例中,編譯器無法堆論出 `p3` 到底有多長的生命週期。查看函式主體內部後顯" +"示,編譯器只有把握假設 `p3` 的生命週期是 `p1` 和 `p2` 中的較短那個。但就像型" +"別一樣,Rust 規定要對函式引數和回傳值的生命週期加上明確註解。" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "Add `'a` appropriately to `left_most`:" +msgstr "請將 `'a` 妥善新增至 `left_most`:" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "" +"This says, \"given p1 and p2 which both outlive `'a`, the return value lives " +"for at least `'a`." +msgstr "" +"這表示,「假設 p1 和 p2 都比 `'a` 長」,回傳值的生命週期至少會為 `'a`。" + +#: src/slices-and-lifetimes/lifetime-annotations.md +msgid "" +"In common cases, lifetimes can be elided, as described on the next slide." +msgstr "一般情況下可以省略生命週期,詳情請見下一張投影片。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "Lifetimes in Function Calls" +msgstr "函式呼叫中的生命週期" + +#: src/slices-and-lifetimes/lifetime-elision.md +#, fuzzy +msgid "" +"Lifetimes for function arguments and return values must be fully specified, " +"but Rust allows lifetimes to be elided in most cases with [a few simple " +"rules](https://doc.rust-lang.org/nomicon/lifetime-elision.html). This is not " +"inference -- it is just a syntactic shorthand." +msgstr "" +"請務必完整指定函式引數和回傳值的生命週期,不過在大部分情況下,Rust 允許使用 " +"[一些簡單規則](https://doc.rust-lang.org/nomicon/lifetime-elision.html) 省略" +"這些生命週期。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "Each argument which does not have a lifetime annotation is given one." +msgstr "凡是沒有生命週期註解的引數都會獲得一個註解。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "" +"If there is only one argument lifetime, it is given to all un-annotated " +"return values." +msgstr "如果只有一個引數生命週期,則會提供給所有未加註的回傳值。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "" +"If there are multiple argument lifetimes, but the first one is for `self`, " +"that lifetime is given to all un-annotated return values." +msgstr "" +"如果有多個引數生命週期,但第一個是要給 `self`,這個生命週期會提供給所有未加註" +"的回傳值。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "In this example, `cab_distance` is trivially elided." +msgstr "您可看到本例中隨意省略了 `cab_distance`。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "" +"The `nearest` function provides another example of a function with multiple " +"references in its arguments that requires explicit annotation." +msgstr "`nearest` 函式提供另一個函式範例,其引數具有多個需要明確註解的參照。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "Try adjusting the signature to \"lie\" about the lifetimes returned:" +msgstr "請試著調整簽章,「謊報」傳回的生命週期:" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "" +"This won't compile, demonstrating that the annotations are checked for " +"validity by the compiler. Note that this is not the case for raw pointers " +"(unsafe), and this is a common source of errors with unsafe Rust." +msgstr "" +"由於這不會執行編譯,表示編譯器已檢查註解是否有效。請注意,原始指標 (不安全) " +"的情況並非如此,這是不安全 Rust 的常見錯誤來源。" + +#: src/slices-and-lifetimes/lifetime-elision.md +msgid "" +"Students may ask when to use lifetimes. Rust borrows _always_ have " +"lifetimes. Most of the time, elision and type inference mean these don't " +"need to be written out. In more complicated cases, lifetime annotations can " +"help resolve ambiguity. Often, especially when prototyping, it's easier to " +"just work with owned data by cloning values where necessary." +msgstr "" +"學生可能會詢問何時該使用生命週期。Rust 的借用「一律」具有生命週期。在大多數情" +"況下,如果採取省略和型別推論的方式,表示您不必編寫這些內容。但在較複雜的情況" +"下,生命週期註解可以協助解決模稜兩可的情況。一般而言,只要在有必要時複製值," +"即可輕鬆處理所擁有的資料,特別是在原型設計階段更是如此。" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "Lifetimes in Data Structures" +msgstr "資料結構中的生命週期" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "" +"If a data type stores borrowed data, it must be annotated with a lifetime:" +msgstr "如果資料型別會儲存借用的資料,則必須使用生命週期註解:" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "\"Bye {text}!\"" +msgstr "\"Bye {text}!\"" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "\"The quick brown fox jumps over the lazy dog.\"" +msgstr "\"The quick brown fox jumps over the lazy dog.\"" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "// erase(text);\n" +msgstr "// erase(text);\n" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "\"{fox:?}\"" +msgstr "\"{fox:?}\"" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "\"{dog:?}\"" +msgstr "\"{dog:?}\"" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "" +"In the above example, the annotation on `Highlight` enforces that the data " +"underlying the contained `&str` lives at least as long as any instance of " +"`Highlight` that uses that data." +msgstr "" +"在上述範例中,`Highlight` 的註解會強制執行以下規定:若是包含在內的 `&str` 的" +"基礎資料,留存時間應至少和使用該資料的所有 `Highlight` 例項一樣長。" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "" +"If `text` is consumed before the end of the lifetime of `fox` (or `dog`), " +"the borrow checker throws an error." +msgstr "" +"如果在 `fox` (或 `dog`) 的生命週期結束前消耗 `text`,借用檢查器會擲回錯誤。" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "" +"Types with borrowed data force users to hold on to the original data. This " +"can be useful for creating lightweight views, but it generally makes them " +"somewhat harder to use." +msgstr "" +"含有借用資料的型別會強制要求使用者保留原始資料。這在建立輕量檢視畫面可能很實" +"用,但通常也會增加使用難度。" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "When possible, make data structures own their data directly." +msgstr "請盡可能讓資料結構直接擁有資料。" + +#: src/slices-and-lifetimes/struct-lifetimes.md +msgid "" +"Some structs with multiple references inside can have more than one lifetime " +"annotation. This can be necessary if there is a need to describe lifetime " +"relationships between the references themselves, in addition to the lifetime " +"of the struct itself. Those are very advanced use cases." +msgstr "" +"某些內含多個參照的結構體可擁有多個生命週期註解。如果除了結構體的生命週期之" +"外,還需要描述參照之間的生命週期關係,就可能有必要擁有多個生命週期註解。那些" +"是相當進階的用途。" + +#: src/slices-and-lifetimes/exercise.md +msgid "" +"In this exercise, you will build a parser for the [protobuf binary encoding]" +"(https://protobuf.dev/programming-guides/encoding/). Don't worry, it's " +"simpler than it seems! This illustrates a common parsing pattern, passing " +"slices of data. The underlying data itself is never copied." +msgstr "" +"在本練習中,您將建構 [protobuf 二進位編碼](https://protobuf.dev/programming-" +"guides/encoding/)的剖析器。請放心,這比看起來容易!這個練習也會舉例說明常見的" +"剖析模式,也就是傳遞資料切片。基礎資料本身一律不會複製。" + +#: src/slices-and-lifetimes/exercise.md +msgid "" +"Fully parsing a protobuf message requires knowing the types of the fields, " +"indexed by their field numbers. That is typically provided in a `proto` " +"file. In this exercise, we'll encode that information into `match` " +"statements in functions that get called for each field." +msgstr "" +"如要完整剖析 protobuf 訊息,您必須瞭解欄位型別,這會依欄位編號建立索引,通常" +"位於 `proto` 檔案內。在本練習中,我們會在針對各欄位呼叫的函式中,將該資訊編碼" +"為 `match` 陳述式。" + +#: src/slices-and-lifetimes/exercise.md +msgid "We'll use the following proto:" +msgstr "我們將使用以下 proto:" + +#: src/slices-and-lifetimes/exercise.md +msgid "" +"A proto message is encoded as a series of fields, one after the next. Each " +"is implemented as a \"tag\" followed by the value. The tag contains a field " +"number (e.g., `2` for the `id` field of a `Person` message) and a wire type " +"defining how the payload should be determined from the byte stream." +msgstr "" +"proto 訊息會編碼為一系列的欄位,一個接著一個。每個欄位都以後方加上值的「標" +"記」形式實作。此標記含有欄位編號 (例如 `Person` 訊息的 `id` 欄位編號是 `2`) " +"以及有線型別,後者負責定義應如何從位元組資料流中決定酬載。" + +#: src/slices-and-lifetimes/exercise.md +msgid "" +"Integers, including the tag, are represented with a variable-length encoding " +"called VARINT. Luckily, `parse_varint` is defined for you below. The given " +"code also defines callbacks to handle `Person` and `PhoneNumber` fields, and " +"to parse a message into a series of calls to those callbacks." +msgstr "" +"整數 (包含標記) 會以稱為 VARINT 的可變長度編碼表示。好消息是,以下程式碼已為" +"您定義 `parse_varint`。該程式碼也定義了回呼,藉此處理 `Person` 和 " +"`PhoneNumber` 欄位,並將訊息剖析為對這些回呼的一系列呼叫。" + +#: src/slices-and-lifetimes/exercise.md +msgid "" +"What remains for you is to implement the `parse_field` function and the " +"`ProtoMessage` trait for `Person` and `PhoneNumber`." +msgstr "" +"您剩下的就只是為 `Person` 和 `PhoneNumber` 實作 `parse_field` 函式和 " +"`ProtoMessage` 特徵即可。" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "\"Invalid varint\"" +msgstr "\"Invalid varint\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "\"Invalid wire-type\"" +msgstr "\"Invalid wire-type\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "\"Unexpected EOF\"" +msgstr "\"Unexpected EOF\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "\"Invalid length\"" +msgstr "\"Invalid length\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "\"Unexpected wire-type)\"" +msgstr "\"Unexpected wire-type)\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "\"Invalid string (not UTF-8)\"" +msgstr "\"Invalid string (not UTF-8)\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "/// A wire type as seen on the wire.\n" +msgstr "/// A wire type as seen on the wire.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "/// The Varint WireType indicates the value is a single VARINT.\n" +msgstr "/// The Varint WireType indicates the value is a single VARINT.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "" +"//I64, -- not needed for this exercise\n" +" /// The Len WireType indicates that the value is a length represented as " +"a\n" +" /// VARINT followed by exactly that number of bytes.\n" +msgstr "" +"//I64, -- not needed for this exercise\n" +" /// The Len WireType indicates that the value is a length represented as " +"a\n" +" /// VARINT followed by exactly that number of bytes.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "" +"/// The I32 WireType indicates that the value is precisely 4 bytes in\n" +" /// little-endian order containing a 32-bit signed integer.\n" +msgstr "" +"/// The I32 WireType indicates that the value is precisely 4 bytes in\n" +" /// little-endian order containing a 32-bit signed integer.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "/// A field's value, typed based on the wire type.\n" +msgstr "/// A field's value, typed based on the wire type.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "//I64(i64), -- not needed for this exercise\n" +msgstr "//I64(i64), -- not needed for this exercise\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "/// A field, containing the field number and its value.\n" +msgstr "/// A field, containing the field number and its value.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "//1 => WireType::I64, -- not needed for this exercise\n" +msgstr "//1 => WireType::I64, -- not needed for this exercise\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "" +"/// Parse a VARINT, returning the parsed value and the remaining bytes.\n" +msgstr "" +"/// Parse a VARINT, returning the parsed value and the remaining bytes.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "" +"// This is the last byte of the VARINT, so convert it to\n" +" // a u64 and return it.\n" +msgstr "" +"// This is the last byte of the VARINT, so convert it to\n" +" // a u64 and return it.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "// More than 7 bytes is invalid.\n" +msgstr "// More than 7 bytes is invalid.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "/// Convert a tag into a field number and a WireType.\n" +msgstr "/// Convert a tag into a field number and a WireType.\n" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "/// Parse a field, returning the remaining bytes\n" +msgstr "/// Parse a field, returning the remaining bytes\n" + +#: src/slices-and-lifetimes/exercise.md +msgid "" +"\"Based on the wire type, build a Field, consuming as many bytes as " +"necessary.\"" +msgstr "" +"\"Based on the wire type, build a Field, consuming as many bytes as " +"necessary.\"" + +#: src/slices-and-lifetimes/exercise.md +msgid "\"Return the field, and any un-consumed bytes.\"" +msgstr "\"Return the field, and any un-consumed bytes.\"" + +#: src/slices-and-lifetimes/exercise.md src/slices-and-lifetimes/solution.md +msgid "" +"/// Parse a message in the given data, calling `T::add_field` for each field " +"in\n" +"/// the message.\n" +"///\n" +"/// The entire input is consumed.\n" +msgstr "" +"/// Parse a message in the given data, calling `T::add_field` for each field " +"in\n" +"/// the message.\n" +"///\n" +"/// The entire input is consumed.\n" + +#: src/slices-and-lifetimes/exercise.md +msgid "// TODO: Implement ProtoMessage for Person and PhoneNumber.\n" +msgstr "// TODO: Implement ProtoMessage for Person and PhoneNumber.\n" + +#: src/slices-and-lifetimes/solution.md +msgid "// Unwrap error because `value` is definitely 4 bytes long.\n" +msgstr "// Unwrap error because `value` is definitely 4 bytes long.\n" + +#: src/slices-and-lifetimes/solution.md +msgid "// skip everything else\n" +msgstr "// skip everything else\n" + +#: src/slices-and-lifetimes/solution.md +msgid "b\"hello\"" +msgstr "b\"hello\"" + +#: src/welcome-day-4.md +msgid "Welcome to Day 4" +msgstr "歡迎參加第 4 天課程" + +#: src/welcome-day-4.md +#, fuzzy +msgid "" +"Today we will cover topics relating to building large-scale software in Rust:" +msgstr "今天我們會探討一些有關 Rust 的進階主題:" + +#: src/welcome-day-4.md +msgid "Iterators: a deep dive on the `Iterator` trait." +msgstr "疊代器:深入探討 `Iterator` 特徵。" + +#: src/welcome-day-4.md +msgid "Modules and visibility." +msgstr "模組和可見性。" + +#: src/welcome-day-4.md +msgid "Testing." +msgstr "測試。" + +#: src/welcome-day-4.md +msgid "Error handling: panics, `Result`, and the try operator `?`." +msgstr "錯誤處理:恐慌、`Result`,以及 try 運算子 `?`。" + +#: src/welcome-day-4.md +msgid "" +"Unsafe Rust: the escape hatch when you can't express yourself in safe Rust." +msgstr "不安全的 Rust:不能寫出安全的 Rust 時的應急方法。" + +#: src/welcome-day-4.md +msgid "[Welcome](./welcome-day-4.md) (3 minutes)" +msgstr "[歡迎](./welcome-day-4.md) (3 分鐘)" + +#: src/welcome-day-4.md +msgid "[Iterators](./iterators.md) (45 minutes)" +msgstr "[疊代器](./iterators.md) (45 分鐘)" + +#: src/welcome-day-4.md +msgid "[Modules](./modules.md) (40 minutes)" +msgstr "[模組](./modules.md) (40 分鐘)" + +#: src/welcome-day-4.md +msgid "[Testing](./testing.md) (45 minutes)" +msgstr "[測試](./testing.md) (45 分鐘)" + +#: src/welcome-day-4.md +msgid "" +"Including 10 minute breaks, this session should take about 2 hours and 40 " +"minutes" +msgstr "加上 10 分鐘的休息時間,這個課程大約需要 2 小時 40 分鐘" + +#: src/iterators.md +msgid "[Iterator](./iterators/iterator.md) (5 minutes)" +msgstr "[疊代器](./iterators/iterator.md) (5 分鐘)" + +#: src/iterators.md +msgid "[IntoIterator](./iterators/intoiterator.md) (5 minutes)" +msgstr "[IntoIterator](./iterators/intoiterator.md) (5 分鐘)" + +#: src/iterators.md +msgid "[FromIterator](./iterators/fromiterator.md) (5 minutes)" +msgstr "[FromIterator](./iterators/fromiterator.md) (5 分鐘)" + +#: src/iterators.md +msgid "" +"[Exercise: Iterator Method Chaining](./iterators/exercise.md) (30 minutes)" +msgstr "[練習:疊代器方法鏈結](./iterators/exercise.md) (30 分鐘)" + +#: src/iterators/iterator.md +msgid "" +"The [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) " +"trait supports iterating over values in a collection. It requires a `next` " +"method and provides lots of methods. Many standard library types implement " +"`Iterator`, and you can implement it yourself, too:" +msgstr "" +"[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) 特徵可讓" +"您對集合中的值進行疊代作業。這需要用到 `next` 方法,且會提供大量方法。許多標" +"準程式庫型別都能實作 `Iterator`,而您也可以自行實作:" + +#: src/iterators/iterator.md +msgid "\"fib({i}): {n}\"" +msgstr "\"fib({i}): {n}\"" + +#: src/iterators/iterator.md +#, fuzzy +msgid "" +"The `Iterator` trait implements many common functional programming " +"operations over collections (e.g. `map`, `filter`, `reduce`, etc). This is " +"the trait where you can find all the documentation about them. In Rust these " +"functions should produce the code as efficient as equivalent imperative " +"implementations." +msgstr "" +"`Iterator` 特徵會對集合實作許多常見的函式程式操作,例如 `map`、`filter`、 " +"`reduce` 等等。您可以藉由此特徵找出所有相關的說明文件。在 Rust 中,這些 函式" +"會產生程式碼,且應與對應的命令式實作項目一樣有效率。" + +#: src/iterators/iterator.md +msgid "" +"`IntoIterator` is the trait that makes for loops work. It is implemented by " +"collection types such as `Vec` and references to them such as `&Vec` " +"and `&[T]`. Ranges also implement it. This is why you can iterate over a " +"vector with `for i in some_vec { .. }` but `some_vec.next()` doesn't exist." +msgstr "" +"`IntoIterator` 是迫使 for 迴圈運作的特徵。此特徵由集合型別(例如 `Vec`) " +"和相關參照 (`&Vec` 與 `&[T]`) 實作而成。此外,範圍也會實作這項特徵。 這就" +"說明了您為何可以透過 `for i in some_vec { .. }` 對向量進行疊代,即使沒有 " +"`some_vec.next()` 也無妨。" + +#: src/iterators/intoiterator.md +#, fuzzy +msgid "" +"The `Iterator` trait tells you how to _iterate_ once you have created an " +"iterator. The related trait [`IntoIterator`](https://doc.rust-lang.org/std/" +"iter/trait.IntoIterator.html) defines how to create an iterator for a type. " +"It is used automatically by the `for` loop." +msgstr "" +"`Iterator` 特徵會告訴您如何在建立疊代器後進行「疊代」。相關特徵 " +"`IntoIterator` 則會說明如何建立疊代器:" + +#: src/iterators/intoiterator.md +msgid "\"point = {x}, {y}\"" +msgstr "\"point = {x}, {y}\"" + +#: src/iterators/intoiterator.md +#, fuzzy +msgid "" +"Click through to the docs for `IntoIterator`. Every implementation of " +"`IntoIterator` must declare two types:" +msgstr "這裡的語法表示每個 `IntoIterator` 的實作都必須宣告兩種型別:" + +#: src/iterators/intoiterator.md +#, fuzzy +msgid "`Item`: the type to iterate over, such as `i8`," +msgstr "`Item`:進行疊代的型別,例如 `i8`。" + +#: src/iterators/intoiterator.md +msgid "`IntoIter`: the `Iterator` type returned by the `into_iter` method." +msgstr "`IntoIter`:`into_iter` 方法傳回的 `Iterator` 型別。" + +#: src/iterators/intoiterator.md +msgid "" +"Note that `IntoIter` and `Item` are linked: the iterator must have the same " +"`Item` type, which means that it returns `Option`" +msgstr "" +"請注意,`IntoIter` 和 `Item` 已建立連結:疊代器必須具有相同的 `Item` 型別,表" +"示會傳回 `Option`。" + +#: src/iterators/intoiterator.md +msgid "The example iterates over all combinations of x and y coordinates." +msgstr "此範例會對 x 和 y 座標的所有組合進行疊代。" + +#: src/iterators/intoiterator.md +msgid "" +"Try iterating over the grid twice in `main`. Why does this fail? Note that " +"`IntoIterator::into_iter` takes ownership of `self`." +msgstr "" +"請嘗試在 `main` 中對格線疊代兩次。想想為什麼這樣會失敗?請注意," +"`IntoIterator::into_iter` 會取得 `self` 的擁有權。" + +#: src/iterators/intoiterator.md +msgid "" +"Fix this issue by implementing `IntoIterator` for `&Grid` and storing a " +"reference to the `Grid` in `GridIter`." +msgstr "" +"如要修正此問題,請針對 `&Grid` 實作 `IntoIterator`,並將 `Grid` 的參照儲存在 " +"`GridIter` 中。" + +#: src/iterators/intoiterator.md +msgid "" +"The same problem can occur for standard library types: `for e in " +"some_vector` will take ownership of `some_vector` and iterate over owned " +"elements from that vector. Use `for e in &some_vector` instead, to iterate " +"over references to elements of `some_vector`." +msgstr "" +"標準程式庫型別可能會發生同樣的問題,也就是 `for e in some_vector` 會取得 " +"`some_vector` 的擁有權,並對該向量內擁有的元素進行疊代。因此,請改用 `for e " +"in &some_vector` 疊代處理對 `some_vector` 元素的參照。" + +#: src/iterators/fromiterator.md +msgid "FromIterator" +msgstr "FromIterator" + +#: src/iterators/fromiterator.md +msgid "" +"[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) " +"lets you build a collection from an [`Iterator`](https://doc.rust-lang.org/" +"std/iter/trait.Iterator.html)." +msgstr "" +"[`FromIterator`](https://doc.rust-lang.org/std/iter/trait.FromIterator.html) " +"可讓您透過 [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator." +"html) 建構集合。" + +#: src/iterators/fromiterator.md +msgid "\"prime_squares: {prime_squares:?}\"" +msgstr "\"prime_squares: {prime_squares:?}\"" + +#: src/iterators/fromiterator.md +#, fuzzy +msgid "`Iterator` implements" +msgstr "`Iterator`" + +#: src/iterators/fromiterator.md +msgid "There are two ways to specify `B` for this method:" +msgstr "您可以透過兩種方式為這個方法指定 `B`:" + +#: src/iterators/fromiterator.md +msgid "" +"With the \"turbofish\": `some_iterator.collect::()`, as " +"shown. The `_` shorthand used here lets Rust infer the type of the `Vec` " +"elements." +msgstr "" +"依指示使用「turbofish」:`some_iterator.collect::()`。在這裡" +"使用 `_` 簡寫,可讓 Rust 推論 `Vec` 元素的型別。" + +#: src/iterators/fromiterator.md +msgid "" +"With type inference: `let prime_squares: Vec<_> = some_iterator.collect()`. " +"Rewrite the example to use this form." +msgstr "" +"使用型別推論:`let prime_squares: Vec<_> = some_iterator.collect()`。請重新編" +"寫這個例子,採用這個形式。" + +#: src/iterators/fromiterator.md +#, fuzzy +msgid "" +"There are basic implementations of `FromIterator` for `Vec`, `HashMap`, etc. " +"There are also more specialized implementations which let you do cool things " +"like convert an `Iterator>` into a `Result, E>`." +msgstr "" +"您也可以利用部分實作項目完成某些酷炫操作,例如將 `Iterator>` 轉換成 `Result, E>`。" + +#: src/iterators/exercise.md +#, fuzzy +msgid "" +"In this exercise, you will need to find and use some of the provided methods " +"in the [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) " +"trait to implement a complex calculation." +msgstr "" +"您可以自行在型別上實作 [`Iterator`](https://doc.rust-lang.org/std/iter/trait." +"Iterator.html) 特徵:" + +#: src/iterators/exercise.md +#, fuzzy +msgid "" +"Copy the following code to and make the tests " +"pass. Use an iterator expression and `collect` the result to construct the " +"return value." +msgstr "" +"將下列程式碼複製到 ,然後設法通過測試。請盡量避" +"免為中繼結果分配 `Vec`:" + +#: src/iterators/exercise.md src/iterators/solution.md +msgid "" +"/// Calculate the differences between elements of `values` offset by " +"`offset`,\n" +"/// wrapping around from the end of `values` to the beginning.\n" +"///\n" +"/// Element `n` of the result is `values[(n+offset)%len] - values[n]`.\n" +msgstr "" +"/// Calculate the differences between elements of `values` offset by " +"`offset`,\n" +"/// wrapping around from the end of `values` to the beginning.\n" +"///\n" +"/// Element `n` of the result is `values[(n+offset)%len] - values[n]`.\n" + +#: src/modules.md +msgid "[Modules](./modules/modules.md) (3 minutes)" +msgstr "[模組](./modules/modules.md) (3 分鐘)" + +#: src/modules.md +msgid "[Filesystem Hierarchy](./modules/filesystem.md) (5 minutes)" +msgstr "[檔案系統階層](./modules/filesystem.md) (5 分鐘)" + +#: src/modules.md +msgid "[Visibility](./modules/visibility.md) (5 minutes)" +msgstr "[可見性](./modules/visibility.md) (5 分鐘)" + +#: src/modules.md +msgid "[use, super, self](./modules/paths.md) (10 minutes)" +msgstr "[use、super、self](./modules/paths.md) (10 分鐘)" + +#: src/modules.md +msgid "" +"[Exercise: Modules for a GUI Library](./modules/exercise.md) (15 minutes)" +msgstr "[練習:GUI 程式庫的模組](./modules/exercise.md) (15 分鐘)" + +#: src/modules/modules.md +msgid "We have seen how `impl` blocks let us namespace functions to a type." +msgstr "我們已介紹 `impl` 區塊如何讓我們將函式的命名空間建立為型別。" + +#: src/modules/modules.md +msgid "Similarly, `mod` lets us namespace types and functions:" +msgstr "同樣地,`mod` 可讓我們建立型別和函式的命名空間:" + +#: src/modules/modules.md +msgid "\"In the foo module\"" +msgstr "\"In the foo module\"" + +#: src/modules/modules.md +msgid "\"In the bar module\"" +msgstr "\"In the bar module\"" + +#: src/modules/modules.md +msgid "" +"Packages provide functionality and include a `Cargo.toml` file that " +"describes how to build a bundle of 1+ crates." +msgstr "" +"套件會提供功能,並收錄 `Cargo.toml` 檔案,用於說明如何建構含有超過 1 個 " +"Crate 的組合。" + +#: src/modules/modules.md +msgid "" +"Crates are a tree of modules, where a binary crate creates an executable and " +"a library crate compiles to a library." +msgstr "" +"Crate 是模組的樹狀結構,其中二進位檔 Crate 會建立執行檔,而程式庫 Crate 則會" +"編譯至程式庫。" + +#: src/modules/modules.md +msgid "Modules define organization, scope, and are the focus of this section." +msgstr "模組不僅會定義組織、範圍,同時也是本節重點。" + +#: src/modules/filesystem.md +msgid "" +"Omitting the module content will tell Rust to look for it in another file:" +msgstr "如果您省略模組內容,系統會指示 Rust 在其他檔案中尋找該內容:" + +#: src/modules/filesystem.md +msgid "" +"This tells rust that the `garden` module content is found at `src/garden." +"rs`. Similarly, a `garden::vegetables` module can be found at `src/garden/" +"vegetables.rs`." +msgstr "" +"這會讓 Rust 知道 `garden` 模組內容是在 `src/garden.rs` 中找到的。同樣地," +"`garden::vegetables` 模組可在 `src/garden/vegetables.rs` 中找到。" + +#: src/modules/filesystem.md +msgid "The `crate` root is in:" +msgstr "`crate` 根層級位於:" + +#: src/modules/filesystem.md +msgid "`src/lib.rs` (for a library crate)" +msgstr "`src/lib.rs` (適用於程式庫 Crate)" + +#: src/modules/filesystem.md +msgid "`src/main.rs` (for a binary crate)" +msgstr "`src/main.rs` (適用於二進位檔 Crate)" + +#: src/modules/filesystem.md +msgid "" +"Modules defined in files can be documented, too, using \"inner doc " +"comments\". These document the item that contains them -- in this case, a " +"module." +msgstr "" +"您也可以使用 \"inner doc comments\" 記錄檔案中定義的模組。這些會記錄包含它們" +"的項目,在本例中就是模組。" + +#: src/modules/filesystem.md +msgid "" +"//! This module implements the garden, including a highly performant " +"germination\n" +"//! implementation.\n" +msgstr "" +"//! This module implements the garden, including a highly performant " +"germination\n" +"//! implementation.\n" + +#: src/modules/filesystem.md +msgid "// Re-export types from this module.\n" +msgstr "// Re-export types from this module.\n" + +#: src/modules/filesystem.md +msgid "/// Sow the given seed packets.\n" +msgstr "/// Sow the given seed packets.\n" + +#: src/modules/filesystem.md +msgid "/// Harvest the produce in the garden that is ready.\n" +msgstr "/// Harvest the produce in the garden that is ready.\n" + +#: src/modules/filesystem.md +msgid "" +"Before Rust 2018, modules needed to be located at `module/mod.rs` instead of " +"`module.rs`, and this is still a working alternative for editions after 2018." +msgstr "" +"在 Rust 2018 之前,模組需位於 `module/mod.rs` 而非 `module.rs` 中,這仍然是 " +"2018 後續版本的可行替代方案。" + +#: src/modules/filesystem.md +msgid "" +"The main reason to introduce `filename.rs` as alternative to `filename/mod." +"rs` was because many files named `mod.rs` can be hard to distinguish in IDEs." +msgstr "" +"導入 `filename.rs` 做為 `filename/mod.rs` 的替代方案,主要是因為許多名為 " +"`mod.rs` 的檔案在 IDE 中很難區分。" + +#: src/modules/filesystem.md +msgid "Deeper nesting can use folders, even if the main module is a file:" +msgstr "更深層的巢狀結構可以使用資料夾,即使主要模組為檔案也一樣:" + +#: src/modules/filesystem.md +msgid "" +"The place rust will look for modules can be changed with a compiler " +"directive:" +msgstr "Rust 尋找模組的位置可透過編譯器指令變更:" + +#: src/modules/filesystem.md +msgid "\"some/path.rs\"" +msgstr "\"some/path.rs\"" + +#: src/modules/filesystem.md +msgid "" +"This is useful, for example, if you would like to place tests for a module " +"in a file named `some_module_test.rs`, similar to the convention in Go." +msgstr "" +"舉例來說,如果您想將模組的測試放在名為 `some_module_test.rs` 的檔案中 (類似 " +"Go 中的慣例),這就會很實用。" + +#: src/modules/visibility.md +msgid "Modules are a privacy boundary:" +msgstr "我們可將模組視為隱私邊界:" + +#: src/modules/visibility.md +msgid "Module items are private by default (hides implementation details)." +msgstr "模組項目預設為不公開 (會隱藏實作詳細資料)。" + +#: src/modules/visibility.md +msgid "Parent and sibling items are always visible." +msgstr "父項和同層項目一律會顯示。" + +#: src/modules/visibility.md +msgid "" +"In other words, if an item is visible in module `foo`, it's visible in all " +"the descendants of `foo`." +msgstr "換句話說,如果項目顯示在 `foo` 模組中,則會出現在 `foo` 的所有子系中。" + +#: src/modules/visibility.md +msgid "\"outer::private\"" +msgstr "\"outer::private\"" + +#: src/modules/visibility.md +msgid "\"outer::public\"" +msgstr "\"outer::public\"" + +#: src/modules/visibility.md +msgid "\"outer::inner::private\"" +msgstr "\"outer::inner::private\"" + +#: src/modules/visibility.md +msgid "\"outer::inner::public\"" +msgstr "\"outer::inner::public\"" + +#: src/modules/visibility.md +msgid "Use the `pub` keyword to make modules public." +msgstr "使用 `pub` 關鍵字將模組設為公開。" + +#: src/modules/visibility.md +msgid "" +"Additionally, there are advanced `pub(...)` specifiers to restrict the scope " +"of public visibility." +msgstr "此外,您也可以使用進階的 `pub(...)` 指定碼來限制公開的瀏覽權限範圍。" + +#: src/modules/visibility.md +msgid "" +"See the [Rust Reference](https://doc.rust-lang.org/reference/visibility-and-" +"privacy.html#pubin-path-pubcrate-pubsuper-and-pubself)." +msgstr "" +"請參閱 [Rust 參考資料](https://doc.rust-lang.org/reference/visibility-and-" +"privacy.html#pubin-path-pubcrate-pubsuper-and-pubself)。" + +#: src/modules/visibility.md +msgid "Configuring `pub(crate)` visibility is a common pattern." +msgstr "設定 `pub(crate)` 瀏覽權限是一種常見模式。" + +#: src/modules/visibility.md +msgid "Less commonly, you can give visibility to a specific path." +msgstr "您也可以授予特定路徑的瀏覽權限,但這較不常見。" + +#: src/modules/visibility.md +msgid "" +"In any case, visibility must be granted to an ancestor module (and all of " +"its descendants)." +msgstr "無論如何,都請務必將瀏覽權限授予祖系模組 (及其所有子系)。" + +#: src/modules/paths.md +msgid "use, super, self" +msgstr "use、super、self" + +#: src/modules/paths.md +msgid "" +"A module can bring symbols from another module into scope with `use`. You " +"will typically see something like this at the top of each module:" +msgstr "" +"模組可以使用 `use` 將其他模組的符號帶進範圍內。您通常會在每個模組的頂端看到類" +"似下方的內容:" + +#: src/modules/paths.md +msgid "Paths" +msgstr "路徑" + +#: src/modules/paths.md +msgid "Paths are resolved as follows:" +msgstr "路徑的解析方式包括:" + +#: src/modules/paths.md +msgid "As a relative path:" +msgstr "做為相對路徑:" + +#: src/modules/paths.md +msgid "`foo` or `self::foo` refers to `foo` in the current module," +msgstr "`foo` 或 `self::foo` 是指目前模組中的 `foo`。" + +#: src/modules/paths.md +msgid "`super::foo` refers to `foo` in the parent module." +msgstr "`super::foo` 是指父項模組中的 `foo`。" + +#: src/modules/paths.md +msgid "As an absolute path:" +msgstr "做為絕對路徑:" + +#: src/modules/paths.md +msgid "`crate::foo` refers to `foo` in the root of the current crate," +msgstr "`crate::foo` 是指目前 Crate 根目錄中的 `foo`。" + +#: src/modules/paths.md +msgid "`bar::foo` refers to `foo` in the `bar` crate." +msgstr "`bar::foo` 是指 `bar` Crate 中的 `foo`。" + +#: src/modules/paths.md +msgid "" +"It is common to \"re-export\" symbols at a shorter path. For example, the " +"top-level `lib.rs` in a crate might have" +msgstr "" +"常見的方式是在較短的路徑上「重新導出」符號。舉例來說,Crate 中的頂層 `lib." +"rs` 可能有" + +#: src/modules/paths.md +msgid "" +"making `DiskStorage` and `NetworkStorage` available to other crates with a " +"convenient, short path." +msgstr "透過便捷的短路徑,向其他 Crate 提供 `DiskStorage` 和`NetworkStorage`。" + +#: src/modules/paths.md +msgid "" +"For the most part, only items that appear in a module need to be `use`'d. " +"However, a trait must be in scope to call any methods on that trait, even if " +"a type implementing that trait is already in scope. For example, to use the " +"`read_to_string` method on a type implementing the `Read` trait, you need to " +"`use std::io::Read`." +msgstr "" +"在大部分情況下,只有顯示在模組中的項目需要 `use`。但是,如要呼叫特徵的任何方" +"法,該特徵必須處於範圍之內,即使實作該特徵的型別已在範圍內也一樣。舉例來說," +"如要在實作 `Read` 特徵的型別上使用 `read_to_string` 方法,您需要 `use std::" +"io::Read`。" + +#: src/modules/paths.md +msgid "" +"The `use` statement can have a wildcard: `use std::io::*`. This is " +"discouraged because it is not clear which items are imported, and those " +"might change over time." +msgstr "" +"`use` 陳述式可能包含萬用字元,例如 `use std::io::*`。不過,這不是建議的做法," +"因為我們無法確定匯入了哪些項目,而且這些項目可能隨著時間改變。" + +#: src/modules/exercise.md +msgid "" +"In this exercise, you will reorganize a small GUI Library implementation. " +"This library defines a `Widget` trait and a few implementations of that " +"trait, as well as a `main` function." +msgstr "" +"在本練習中,您將重新編排小型的 GUI 程式庫實作項目。這個程式庫定義了 `Widget` " +"特徵、該特徵的幾個實作項目,以及 `main` 函式。" + +#: src/modules/exercise.md +msgid "" +"It is typical to put each type or set of closely-related types into its own " +"module, so each widget type should get its own module." +msgstr "" +"通常,每種型別 (或一組密切相關的型別) 會放入各自的模組中,因此每個小工具型別" +"應該都有自己的模組。" + +#: src/modules/exercise.md +#, fuzzy +msgid "Cargo Setup" +msgstr "設定" + +#: src/modules/exercise.md +msgid "" +"The Rust playground only supports one file, so you will need to make a Cargo " +"project on your local filesystem:" +msgstr "" +"Rust Playground 僅支援一個檔案,因此您需要在本機檔案系統中建立 Cargo 專案:" + +#: src/modules/exercise.md +msgid "" +"Edit the resulting `src/main.rs` to add `mod` statements, and add additional " +"files in the `src` directory." +msgstr "" +"請編輯產生的 `src/main.rs`,新增 `mod` 陳述式並在 `src` 目錄中新增其他檔案。" + +#: src/modules/exercise.md +msgid "Source" +msgstr "來源" + +#: src/modules/exercise.md +msgid "Here's the single-module implementation of the GUI library:" +msgstr "以下是 GUI 程式庫的單一模組實作項目:" + +#: src/modules/exercise.md src/modules/solution.md +msgid "/// Natural width of `self`.\n" +msgstr "/// Natural width of `self`.\n" + +#: src/modules/exercise.md src/modules/solution.md +msgid "/// Draw the widget into a buffer.\n" +msgstr "/// Draw the widget into a buffer.\n" + +#: src/modules/exercise.md src/modules/solution.md +msgid "/// Draw the widget on standard output.\n" +msgstr "/// Draw the widget on standard output.\n" + +#: src/modules/exercise.md src/modules/solution.md +msgid "\"{buffer}\"" +msgstr "\"{buffer}\"" + +#: src/modules/exercise.md +msgid "// Add 4 paddings for borders\n" +msgstr "// Add 4 paddings for borders\n" + +#: src/modules/exercise.md +msgid "" +"// TODO: Change draw_into to return Result<(), std::fmt::Error>. Then use " +"the\n" +" // ?-operator here instead of .unwrap().\n" +msgstr "" +"// TODO: Change draw_into to return Result<(), std::fmt::Error>. Then use " +"the\n" +" // ?-operator here instead of .unwrap().\n" + +#: src/modules/exercise.md src/modules/solution.md +msgid "\"+-{:-. Then use\n" +" // the ?-operator here instead of .unwrap().\n" +msgstr "" +"// TODO: after learning about error handling, you can change\n" +" // draw_into to return Result<(), std::fmt::Error>. Then use\n" +" // the ?-operator here instead of .unwrap().\n" + +#: src/modules/solution.md +msgid "// ---- src/main.rs ----\n" +msgstr "// ---- src/main.rs ----\n" + +#: src/testing.md +msgid "[Test Modules](./testing/unit-tests.md) (5 minutes)" +msgstr "[測試模組](./testing/unit-tests.md) (5 分鐘)" + +#: src/testing.md +msgid "[Other Types of Tests](./testing/other.md) (5 minutes)" +msgstr "[其他測試類型](./testing/other.md) (5 分鐘)" + +#: src/testing.md +msgid "[Compiler Lints and Clippy](./testing/lints.md) (3 minutes)" +msgstr "[編譯器 Lint 和 Clippy](./testing/lints.md) (3 分鐘)" + +#: src/testing.md +msgid "[Exercise: Luhn Algorithm](./testing/exercise.md) (30 minutes)" +msgstr "[練習:盧恩 (Luhn) 演算法](./testing/exercise.md) (30 分鐘)" + +#: src/testing/unit-tests.md +msgid "Unit Tests" +msgstr "單元測試" + +#: src/testing/unit-tests.md msgid "Rust and Cargo come with a simple unit test framework:" msgstr "Rust 和 Cargo 提供了一個簡單的單元測試 (unit test) 框架:" -#: src/testing.md:5 +#: src/testing/unit-tests.md msgid "Unit tests are supported throughout your code." msgstr "在你的程式碼的任何地方都可添加單元測試。" -#: src/testing.md:7 +#: src/testing/unit-tests.md msgid "Integration tests are supported via the `tests/` directory." msgstr "整合測試 (integration test) 則可放置在 `tests/` 資料夾下。" -#: src/testing/unit-tests.md:3 -msgid "Mark unit tests with `#[test]`:" -msgstr "用 `#[test]` 標記單元測試:" - -#: src/testing/unit-tests.md:5 +#: src/testing/unit-tests.md msgid "" -"```rust,editable,ignore\n" -"fn first_word(text: &str) -> &str {\n" -" match text.find(' ') {\n" -" Some(idx) => &text[..idx],\n" -" None => &text,\n" -" }\n" -"}\n" -"\n" -"#[test]\n" -"fn test_empty() {\n" -" assert_eq!(first_word(\"\"), \"\");\n" -"}\n" -"\n" -"#[test]\n" -"fn test_single_word() {\n" -" assert_eq!(first_word(\"Hello\"), \"Hello\");\n" -"}\n" -"\n" -"#[test]\n" -"fn test_multiple_words() {\n" -" assert_eq!(first_word(\"Hello World\"), \"Hello\");\n" -"}\n" -"```" +"Tests are marked with `#[test]`. Unit tests are often put in a nested " +"`tests` module, using `#[cfg(test)]` to conditionally compile them only when " +"building tests." msgstr "" +"測試會以 `#[test]` 標示。單元測試通常會位於巢狀的 `tests` 模組中,使用 " +"`#[cfg(test)]` 可有條件地編譯測試 (僅限在建構測試時)。" -#: src/testing/unit-tests.md:29 -msgid "Use `cargo test` to find and run the unit tests." -msgstr "用 `cargo test` 尋找並執行單元測試。" +#: src/testing/unit-tests.md +#, fuzzy +msgid "\"Hello World\"" +msgstr "Hello World!" -#: src/testing/test-modules.md:3 -msgid "" -"Unit tests are often put in a nested module (run tests on the [Playground]" -"(https://play.rust-lang.org/)):" -msgstr "" -"單元測試通常會位於巢狀模組中 (在 [Playground](https://play.rust-lang.org/) 上" -"執行測試):" - -#: src/testing/test-modules.md:6 -msgid "" -"```rust,editable\n" -"fn helper(a: &str, b: &str) -> String {\n" -" format!(\"{a} {b}\")\n" -"}\n" -"\n" -"pub fn main() {\n" -" println!(\"{}\", helper(\"Hello\", \"World\"));\n" -"}\n" -"\n" -"#[cfg(test)]\n" -"mod tests {\n" -" use super::*;\n" -"\n" -" #[test]\n" -" fn test_helper() {\n" -" assert_eq!(helper(\"foo\", \"bar\"), \"foo bar\");\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/testing/test-modules.md:26 +#: src/testing/unit-tests.md msgid "This lets you unit test private helpers." msgstr "這有助於您對私人輔助程式進行單元測試。" -#: src/testing/test-modules.md:27 +#: src/testing/unit-tests.md msgid "The `#[cfg(test)]` attribute is only active when you run `cargo test`." msgstr "只有在執行 `cargo test` 時,`#[cfg(test)]` 屬性才會生效。" -#: src/testing/doc-tests.md:3 +#: src/testing/unit-tests.md +msgid "Run the tests in the playground in order to show their results." +msgstr "請在 Playground 中執行測試以顯示結果。" + +#: src/testing/other.md +msgid "Integration Tests" +msgstr "整合測試" + +#: src/testing/other.md +msgid "If you want to test your library as a client, use an integration test." +msgstr "如果您要以用戶端身分測試程式庫,請採用整合測試。" + +#: src/testing/other.md +msgid "Create a `.rs` file under `tests/`:" +msgstr "在 `tests/` 之下建立一個 `.rs` 檔案:" + +#: src/testing/other.md +msgid "// tests/my_library.rs\n" +msgstr "// tests/my_library.rs\n" + +#: src/testing/other.md +msgid "These tests only have access to the public API of your crate." +msgstr "這些測試只能存取 crate 的公用 API。" + +#: src/testing/other.md +msgid "Documentation Tests" +msgstr "說明文件測試" + +#: src/testing/other.md msgid "Rust has built-in support for documentation tests:" msgstr "Rust 內建說明文件測試相關支援:" -#: src/testing/doc-tests.md:5 +#: src/testing/other.md msgid "" -"```rust\n" "/// Shortens a string to the given length.\n" "///\n" "/// ```\n" -"/// use playground::shorten_string;\n" +"/// # use playground::shorten_string;\n" "/// assert_eq!(shorten_string(\"Hello World\", 5), \"Hello\");\n" "/// assert_eq!(shorten_string(\"Hello World\", 20), \"Hello World\");\n" "/// ```\n" -"pub fn shorten_string(s: &str, length: usize) -> &str {\n" -" &s[..std::cmp::min(length, s.len())]\n" -"}\n" -"```" msgstr "" +"/// Shortens a string to the given length.\n" +"///\n" +"/// ```\n" +"/// # use playground::shorten_string;\n" +"/// assert_eq!(shorten_string(\"Hello World\", 5), \"Hello\");\n" +"/// assert_eq!(shorten_string(\"Hello World\", 20), \"Hello World\");\n" +"/// ```\n" -#: src/testing/doc-tests.md:18 +#: src/testing/other.md msgid "Code blocks in `///` comments are automatically seen as Rust code." msgstr "系統會自動將 `///` 註解中的程式碼區塊視為 Rust 程式碼。" -#: src/testing/doc-tests.md:19 +#: src/testing/other.md msgid "The code will be compiled and executed as part of `cargo test`." msgstr "系統會編譯程式碼,執行 `cargo test` 時會一併執行這些程式碼。" -#: src/testing/doc-tests.md:20 +#: src/testing/other.md +msgid "" +"Adding `#` in the code will hide it from the docs, but will still compile/" +"run it." +msgstr "程式碼中新增 `#` 後,即可從文件中隱藏,但仍會編譯/執行。" + +#: src/testing/other.md msgid "" "Test the above code on the [Rust Playground](https://play.rust-lang.org/?" "version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0)." @@ -11479,82 +10459,753 @@ msgstr "" "version=stable&mode=debug&edition=2021&gist=3ce2ad13ea1302f6572cb15cd96becf0) " "上測試上述程式碼。" -#: src/testing/integration-tests.md:3 -msgid "If you want to test your library as a client, use an integration test." -msgstr "如果您要以用戶端身分測試程式庫,請採用整合測試。" - -#: src/testing/integration-tests.md:5 -msgid "Create a `.rs` file under `tests/`:" -msgstr "在 `tests/` 之下建立一個 `.rs` 檔案:" - -#: src/testing/integration-tests.md:7 +#: src/testing/lints.md msgid "" -"```rust,ignore\n" -"use my_library::init;\n" -"\n" -"#[test]\n" -"fn test_init() {\n" -" assert!(init().is_ok());\n" -"}\n" -"```" +"The Rust compiler produces fantastic error messages, as well as helpful " +"built-in lints. [Clippy](https://doc.rust-lang.org/clippy/) provides even " +"more lints, organized into groups that can be enabled per-project." msgstr "" +"Rust 編譯器會產生高品質的錯誤訊息,以及實用的內建 Lint。[Clippy](https://doc." +"rust-lang.org/clippy/) 則提供更多 Lint,且會整理成可供每個專案啟用的群組。" -#: src/testing/integration-tests.md:16 -msgid "These tests only have access to the public API of your crate." -msgstr "這些測試只能存取 crate 的公用 API。" +#: src/testing/lints.md +msgid "\"X probably fits in a u16, right? {}\"" +msgstr "\"X probably fits in a u16, right? {}\"" -#: src/testing/useful-crates.md:1 -msgid "Useful crates for writing tests" -msgstr "有助於編寫測試的 crate" - -#: src/testing/useful-crates.md:3 -msgid "Rust comes with only basic support for writing tests." -msgstr "Rust 只提供基本的編寫測試支援。" - -#: src/testing/useful-crates.md:5 -msgid "Here are some additional crates which we recommend for writing tests:" -msgstr "以下列出幾個額外的 crate,建議您在編寫測試時使用:" - -#: src/testing/useful-crates.md:7 +#: src/testing/lints.md msgid "" -"[googletest](https://docs.rs/googletest): Comprehensive test assertion " -"library in the tradition of GoogleTest for C++." +"Run the code sample and examine the error message. There are also lints " +"visible here, but those will not be shown once the code compiles. Switch to " +"the Playground site to show those lints." msgstr "" -"[googletest](https://docs.rs/googletest):這是全面性的測試斷言程式庫,沿用了 " -"GoogleTest (適用於 C++) 的傳統運作方式。" +"請執行程式碼範例並查看錯誤訊息。雖然這裡也能看到 Lint,但程式碼開始編譯後," +"Lint 就不會再顯示。因此若要查看這些 Lint,請改用 Playground 網站。" -#: src/testing/useful-crates.md:8 -msgid "[proptest](https://docs.rs/proptest): Property-based testing for Rust." -msgstr "" -"[proptest](https://docs.rs/proptest):讓您對 Rust 執行以屬性為基礎的測試。" - -#: src/testing/useful-crates.md:9 +#: src/testing/lints.md msgid "" -"[rstest](https://docs.rs/rstest): Support for fixtures and parameterised " -"tests." -msgstr "[rstest](https://docs.rs/rstest):支援 Fixture 和參數化測試。" +"After resolving the lints, run `clippy` on the playground site to show " +"clippy warnings. Clippy has extensive documentation of its lints, and adds " +"new lints (including default-deny lints) all the time." +msgstr "" +"解析 Lint 後,請在 Playground 網站上執行 `clippy`,顯示 clippy 警告。Clippy " +"提供大量 Lint 說明文件,且會一直添加新的 Lint (包括預設拒絕的 Lint)。" -#: src/unsafe.md:3 +#: src/testing/lints.md +msgid "" +"Note that errors or warnings with `help: ...` can be fixed with `cargo fix` " +"or via your editor." +msgstr "" +"請注意,您可以使用 `cargo fix` 或編輯器,修正含有 `help: ...` 的錯誤或警告。" + +#: src/testing/exercise.md +msgid "Luhn Algorithm" +msgstr "盧恩演算法" + +#: src/testing/exercise.md +msgid "" +"The [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) is used " +"to validate credit card numbers. The algorithm takes a string as input and " +"does the following to validate the credit card number:" +msgstr "" +"[盧恩演算法](https://en.wikipedia.org/wiki/Luhn_algorithm)可用於驗證信用卡號" +"碼。這個演算法會將字串做為輸入內容,並執行下列操作來驗證信用卡號碼:" + +#: src/testing/exercise.md +#, fuzzy +msgid "Ignore all spaces. Reject number with fewer than two digits." +msgstr "忽略所有空格。拒絕少於兩位數的號碼。" + +#: src/testing/exercise.md +msgid "" +"Moving from **right to left**, double every second digit: for the number " +"`1234`, we double `3` and `1`. For the number `98765`, we double `6` and `8`." +msgstr "" +"從**右到左**,將偶數位的數字乘二。以數字 `1234` 為例,請將 `3` 和 `1` 乘二;" +"若為數字 `98765`,請將 `6` 和 `8` 乘二。" + +#: src/testing/exercise.md +msgid "" +"After doubling a digit, sum the digits if the result is greater than 9. So " +"doubling `7` becomes `14` which becomes `1 + 4 = 5`." +msgstr "" +"將數字乘二後,如果結果大於 9,請將每位數字相加。所以,`7` 乘二等於 `14`,那麼" +"也就是 `1 + 4 = 5`。" + +#: src/testing/exercise.md +msgid "Sum all the undoubled and doubled digits." +msgstr "將所有數字 (無論是否已乘二) 相加。" + +#: src/testing/exercise.md +msgid "The credit card number is valid if the sum ends with `0`." +msgstr "如果加總所得數字的末位是 `0`,代表信用卡卡號有效。" + +#: src/testing/exercise.md +msgid "" +"The provided code provides a buggy implementation of the luhn algorithm, " +"along with two basic unit tests that confirm that most the algorithm is " +"implemented correctly." +msgstr "" +"這裡提供的程式碼是盧恩演算法的錯誤實作示例,另外還有兩個基本單元測試,用於確" +"認大部分演算法已正確實作。" + +#: src/testing/exercise.md +#, fuzzy +msgid "" +"Copy the code below to and write additional " +"tests to uncover bugs in the provided implementation, fixing any bugs you " +"find." +msgstr "" +"請將以下程式碼複製到 ,並填入缺少的函式和方法:" + +#: src/testing/exercise.md src/testing/solution.md +msgid "\"4263 9826 4026 9299\"" +msgstr "\"4263 9826 4026 9299\"" + +#: src/testing/exercise.md src/testing/solution.md +msgid "\"4539 3195 0343 6467\"" +msgstr "\"4539 3195 0343 6467\"" + +#: src/testing/exercise.md src/testing/solution.md +msgid "\"7992 7398 713\"" +msgstr "\"7992 7398 713\"" + +#: src/testing/exercise.md src/testing/solution.md +msgid "\"4223 9826 4026 9299\"" +msgstr "\"4223 9826 4026 9299\"" + +#: src/testing/exercise.md src/testing/solution.md +msgid "\"4539 3195 0343 6476\"" +msgstr "\"4539 3195 0343 6476\"" + +#: src/testing/exercise.md src/testing/solution.md +msgid "\"8273 1232 7352 0569\"" +msgstr "\"8273 1232 7352 0569\"" + +#: src/testing/solution.md +msgid "// This is the buggy version that appears in the problem.\n" +msgstr "// This is the buggy version that appears in the problem.\n" + +#: src/testing/solution.md +msgid "// This is the solution and passes all of the tests below.\n" +msgstr "// This is the solution and passes all of the tests below.\n" + +#: src/testing/solution.md +msgid "\"1234 5678 1234 5670\"" +msgstr "\"1234 5678 1234 5670\"" + +#: src/testing/solution.md +msgid "\"Is {cc_number} a valid credit card number? {}\"" +msgstr "\"Is {cc_number} a valid credit card number? {}\"" + +#: src/testing/solution.md +msgid "\"yes\"" +msgstr "\"yes\"" + +#: src/testing/solution.md +msgid "\"no\"" +msgstr "\"no\"" + +#: src/testing/solution.md +msgid "\"foo 0 0\"" +msgstr "\"foo 0 0\"" + +#: src/testing/solution.md +msgid "\" \"" +msgstr "\" \"" + +#: src/testing/solution.md +msgid "\" \"" +msgstr "\" \"" + +#: src/testing/solution.md +msgid "\" \"" +msgstr "\" \"" + +#: src/testing/solution.md +msgid "\"0\"" +msgstr "\"0\"" + +#: src/testing/solution.md +msgid "\" 0 0 \"" +msgstr "\" 0 0 \"" + +#: src/welcome-day-4-afternoon.md +msgid "[Error Handling](./error-handling.md) (55 minutes)" +msgstr "[錯誤處理](./error-handling.md) (55 分鐘)" + +#: src/welcome-day-4-afternoon.md +msgid "[Unsafe Rust](./unsafe-rust.md) (1 hour and 5 minutes)" +msgstr "[不安全的 Rust](./unsafe-rust.md) (1 小時 5 分鐘)" + +#: src/error-handling.md +msgid "[Panics](./error-handling/panics.md) (3 minutes)" +msgstr "[恐慌](./error-handling/panics.md) (3 分鐘)" + +#: src/error-handling.md +msgid "[Try Operator](./error-handling/try.md) (5 minutes)" +msgstr "[嘗試運算子](./error-handling/try.md) (5 分鐘)" + +#: src/error-handling.md +msgid "[Try Conversions](./error-handling/try-conversions.md) (5 minutes)" +msgstr "[嘗試轉換](./error-handling/try-conversions.md) (5 分鐘)" + +#: src/error-handling.md +msgid "[Error Trait](./error-handling/error.md) (5 minutes)" +msgstr "[錯誤特徵](./error-handling/error.md) (5 分鐘)" + +#: src/error-handling.md +msgid "" +"[thiserror and anyhow](./error-handling/thiserror-and-anyhow.md) (5 minutes)" +msgstr "" +"[thiserror 和 anyhow](./error-handling/thiserror-and-anyhow.md) (5 分鐘)" + +#: src/error-handling.md +msgid "" +"[Exercise: Rewriting with Result](./error-handling/exercise.md) (30 minutes)" +msgstr "[練習:根據結果重新編寫](./error-handling/exercise.md) (30 分鐘)" + +#: src/error-handling/panics.md +msgid "Rust handles fatal errors with a \"panic\"." +msgstr "Rust 會透過「恐慌」來處理嚴重錯誤。" + +#: src/error-handling/panics.md +msgid "Rust will trigger a panic if a fatal error happens at runtime:" +msgstr "如果執行階段發生重大錯誤,Rust 就會觸發恐慌:" + +#: src/error-handling/panics.md +msgid "\"v[100]: {}\"" +msgstr "\"v[100]: {}\"" + +#: src/error-handling/panics.md +msgid "Panics are for unrecoverable and unexpected errors." +msgstr "恐慌代表發生無法復原的非預期錯誤。" + +#: src/error-handling/panics.md +msgid "Panics are symptoms of bugs in the program." +msgstr "恐慌可以反映程式中的錯誤。" + +#: src/error-handling/panics.md +msgid "Runtime failures like failed bounds checks can panic" +msgstr "執行階段失敗 (例如失敗的邊界檢查) 可能會觸發恐慌" + +#: src/error-handling/panics.md +msgid "Assertions (such as `assert!`) panic on failure" +msgstr "斷言 (例如 `assert!`) 會在失敗時發生恐慌" + +#: src/error-handling/panics.md +msgid "Purpose-specific panics can use the `panic!` macro." +msgstr "針對特定用途的恐慌可以使用 `panic!` 巨集。" + +#: src/error-handling/panics.md +msgid "" +"A panic will \"unwind\" the stack, dropping values just as if the functions " +"had returned." +msgstr "恐慌會「解開」堆疊,此行為捨棄值的方式就像函式已傳回一樣。" + +#: src/error-handling/panics.md +msgid "" +"Use non-panicking APIs (such as `Vec::get`) if crashing is not acceptable." +msgstr "如果無法接受程式崩潰,請使用不會觸發恐慌的 API,例如 `Vec::get`。" + +#: src/error-handling/panics.md +msgid "" +"By default, a panic will cause the stack to unwind. The unwinding can be " +"caught:" +msgstr "根據預設,恐慌會造成解開堆疊。您可以擷取這類動作:" + +#: src/error-handling/panics.md +msgid "\"No problem here!\"" +msgstr "\"No problem here!\"" + +#: src/error-handling/panics.md +msgid "\"{result:?}\"" +msgstr "\"{result:?}\"" + +#: src/error-handling/panics.md +msgid "\"oh no!\"" +msgstr "\"oh no!\"" + +#: src/error-handling/panics.md +msgid "" +"Catching is unusual; do not attempt to implement exceptions with " +"`catch_unwind`!" +msgstr "捕獲是異常行為;請勿嘗試以 `catch_unwind` 實作例外狀況!" + +#: src/error-handling/panics.md +msgid "" +"This can be useful in servers which should keep running even if a single " +"request crashes." +msgstr "" +"如果伺服器需要持續運作 (即使有單一要求崩潰也不例外),這種做法就能派上用場。" + +#: src/error-handling/panics.md +msgid "This does not work if `panic = 'abort'` is set in your `Cargo.toml`." +msgstr "如果您在 `Cargo.toml` 中設定 `panic = 'abort'`,就無法採取此做法。" + +#: src/error-handling/try.md +msgid "" +"Runtime errors like connection-refused or file-not-found are handled with " +"the `Result` type, but matching this type on every call can be cumbersome. " +"The try-operator `?` is used to return errors to the caller. It lets you " +"turn the common" +msgstr "" +"連線遭拒或找不到檔案等執行階段錯誤,都是透過 `Result` 型別來處理,但每次呼叫" +"時都比對此類型可能相當麻煩。try 運算子 `?` 的用途是將錯誤傳回呼叫端,可讓您將" +"下列常見的程式碼" + +#: src/error-handling/try.md +msgid "into the much simpler" +msgstr "轉換成以下較簡潔的程式碼:" + +#: src/error-handling/try.md +#, fuzzy +msgid "We can use this to simplify our error handling code:" +msgstr "我們可以使用這個運算子,簡化錯誤處理程式碼:" + +#: src/error-handling/try.md +msgid "//fs::write(\"config.dat\", \"alice\").unwrap();\n" +msgstr "//fs::write(\"config.dat\", \"alice\").unwrap();\n" + +#: src/error-handling/try.md src/error-handling/try-conversions.md +#: src/error-handling/thiserror-and-anyhow.md +msgid "\"config.dat\"" +msgstr "\"config.dat\"" + +#: src/error-handling/try.md src/error-handling/try-conversions.md +msgid "\"username or error: {username:?}\"" +msgstr "\"username or error: {username:?}\"" + +#: src/error-handling/try.md +msgid "Simplify the `read_username` function to use `?`." +msgstr "請簡化 `read_username` 函式,以便使用 `?`。" + +#: src/error-handling/try.md +msgid "The `username` variable can be either `Ok(string)` or `Err(error)`." +msgstr "`username` 變數可以是 `Ok(string)` 或 `Err(error)`。" + +#: src/error-handling/try.md +msgid "" +"Use the `fs::write` call to test out the different scenarios: no file, empty " +"file, file with username." +msgstr "" +"請使用 `fs::write` 呼叫來測試以下不同情況:沒有檔案、空白檔案、含使用者名稱的" +"檔案。" + +#: src/error-handling/try.md +msgid "" +"Note that `main` can return a `Result<(), E>` as long as it implements `std::" +"process::Termination`. In practice, this means that `E` implements `Debug`. " +"The executable will print the `Err` variant and return a nonzero exit status " +"on error." +msgstr "" +"請注意,只要 `main` 實作 `std::process:Termination`,便可傳回 `Result<(), " +"E>`。實務上,這表示 `E` 會實作 `Debug`。執行檔將顯示 `Err` 變體,並在發生錯誤" +"時傳回非零的結束狀態。" + +#: src/error-handling/try-conversions.md +msgid "" +"The effective expansion of `?` is a little more complicated than previously " +"indicated:" +msgstr "比起先前提到的下列程式碼,`?` 的有效擴展稍微更複雜一點:" + +#: src/error-handling/try-conversions.md +msgid "works the same as" +msgstr "運作方式與以下程式碼相同:" + +#: src/error-handling/try-conversions.md +#, fuzzy +msgid "" +"The `From::from` call here means we attempt to convert the error type to the " +"type returned by the function. This makes it easy to encapsulate errors into " +"higher-level errors." +msgstr "" +"這裡的 `From::from` 呼叫意味著,我們嘗試將錯誤型別轉換成函式回傳的型別:" + +#: src/error-handling/try-conversions.md +msgid "\"IO error: {e}\"" +msgstr "\"IO error: {e}\"" + +#: src/error-handling/try-conversions.md +msgid "\"Found no username in {path}\"" +msgstr "\"Found no username in {path}\"" + +#: src/error-handling/try-conversions.md +#: src/error-handling/thiserror-and-anyhow.md +msgid "//fs::write(\"config.dat\", \"\").unwrap();\n" +msgstr "//fs::write(\"config.dat\", \"\").unwrap();\n" + +#: src/error-handling/try-conversions.md +msgid "" +"The `?` operator must return a value compatible with the return type of the " +"function. For `Result`, it means that the error types have to be compatible. " +"A function that returns `Result` can only use `?` on a value " +"of type `Result` if `ErrorOuter` and `ErrorInner` are the " +"same type or if `ErrorOuter` implements `From`." +msgstr "" +"`?` 運算子必須傳回與函式傳回類型相容的值。如果是 `Result`,表示錯誤類型必須相" +"容。如果是傳回 `Result` 的函式,當 `ErrorOuter` 和 " +"`ErrorInner` 的型別相同、或者 `ErrorOuter` 實作 `From` 時,就只能" +"在 `Result` 型別的值上使用 `?`。" + +#: src/error-handling/try-conversions.md +msgid "" +"A common alternative to a `From` implementation is `Result::map_err`, " +"especially when the conversion only happens in one place." +msgstr "" +"`From` 實作的常見的替代方案是 `Result::map_err`,特別是當轉換只在單一位置發生" +"時更是如此。" + +#: src/error-handling/try-conversions.md +msgid "" +"There is no compatibility requirement for `Option`. A function returning " +"`Option` can use the `?` operator on `Option` for arbitrary `T` and " +"`U` types." +msgstr "" +"`Option` 並沒有相容性規定。如果函式會傳回 `Option`,可以在 `Option` 上" +"將 `?` 運算子用於任意的 `T` 和 `U` 型別。" + +#: src/error-handling/try-conversions.md +msgid "" +"A function that returns `Result` cannot use `?` on `Option` and vice versa. " +"However, `Option::ok_or` converts `Option` to `Result` whereas `Result::ok` " +"turns `Result` into `Option`." +msgstr "" +"傳回 `Result` 的函式無法在 `Option` 上使用 `?`,反之亦然。不過,`Option::" +"ok_or` 會將 `Option` 轉換為 `Result`,而 `Result::ok` 則將 `Result` 轉換為 " +"`Option`。" + +#: src/error-handling/error.md +msgid "Dynamic Error Types" +msgstr "動態錯誤型別" + +#: src/error-handling/error.md +#, fuzzy +msgid "" +"Sometimes we want to allow any type of error to be returned without writing " +"our own enum covering all the different possibilities. The `std::error::" +"Error` trait makes it easy to create a trait object that can contain any " +"error." +msgstr "" +"我們有時會想允許傳回任何型別的錯誤,而不是自行編寫涵蓋所有不同可能性的列舉。" +"`std::error::Error` 可讓這項工作更輕鬆。" + +#: src/error-handling/error.md +msgid "\"count.dat\"" +msgstr "\"count.dat\"" + +#: src/error-handling/error.md +msgid "\"1i3\"" +msgstr "\"1i3\"" + +#: src/error-handling/error.md +msgid "\"Count: {count}\"" +msgstr "\"Count: {count}\"" + +#: src/error-handling/error.md +msgid "\"Error: {err}\"" +msgstr "\"Error: {err}\"" + +#: src/error-handling/error.md +msgid "" +"The `read_count` function can return `std::io::Error` (from file operations) " +"or `std::num::ParseIntError` (from `String::parse`)." +msgstr "" +"`read_count` 函式可以傳回 `std::io::Error` (透過檔案作業) 或 `std::num::" +"ParseIntError` (透過 `String::parse`)。" + +#: src/error-handling/error.md +#, fuzzy +msgid "" +"Boxing errors saves on code, but gives up the ability to cleanly handle " +"different error cases differently in the program. As such it's generally not " +"a good idea to use `Box` in the public API of a library, but it " +"can be a good option in a program where you just want to display the error " +"message somewhere." +msgstr "" +"這可少用一些程式碼,但犧牲掉的是無法在程式中以不同方式乾淨地處理各種錯誤情" +"況。因此,在程式庫的公用 API 中使用 `Box`,通常不是一個理想方式," +"但如果您只想在程式中的某處顯示錯誤訊息,它可能是不錯的選擇。" + +#: src/error-handling/error.md +msgid "" +"Make sure to implement the `std::error::Error` trait when defining a custom " +"error type so it can be boxed. But if you need to support the `no_std` " +"attribute, keep in mind that the `std::error::Error` trait is currently " +"compatible with `no_std` in [nightly](https://github.com/rust-lang/rust/" +"issues/103765) only." +msgstr "" +"定義自訂錯誤型別時,請務必實作 `std::error::Error` 特徵,這樣才能裝箱。不過," +"如果您需要支援 `no_std` 屬性,請留意 `std::error::Error` 特徵目前僅與[每夜版]" +"(https://github.com/rust-lang/rust/issues/103765)中的 `no_std` 相容。" + +#: src/error-handling/thiserror-and-anyhow.md +#, fuzzy +msgid "" +"The [`thiserror`](https://docs.rs/thiserror/) and [`anyhow`](https://docs.rs/" +"anyhow/) crates are widely used to simplify error handling." +msgstr "" +"[thiserror](https://docs.rs/thiserror/) crate 很常用來建立錯誤列舉,我們在上" +"一頁就曾這麼做:" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"`thiserror` is often used in libraries to create custom error types that " +"implement `From`." +msgstr "" +"`thiserror` 經常在程式庫中使用,目的是建立可實作 `From` 的自訂錯誤型別。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"`anyhow` is often used by applications to help with error handling in " +"functions, including adding contextual information to your errors." +msgstr "" +"`anyhow` 經常由應用程式使用,目的是協助函式中的錯誤處理機制,包括為錯誤加上背" +"景資訊。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "\"Found no username in {0}\"" +msgstr "\"Found no username in {0}\"" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "\"Failed to open {path}\"" +msgstr "\"Failed to open {path}\"" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "\"Failed to read\"" +msgstr "\"Failed to read\"" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "\"Username: {username}\"" +msgstr "\"Username: {username}\"" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "\"Error: {err:?}\"" +msgstr "\"Error: {err:?}\"" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "`thiserror`" +msgstr "`thiserror`" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"The `Error` derive macro is provided by `thiserror`, and has lots of useful " +"attributes to help define error types in a compact way." +msgstr "" +"`Error` 衍生巨集是由 `thiserror` 提供,附有許多實用的屬性,有助於以精簡方式定" +"義錯誤型別。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "The `std::error::Error` trait is derived automatically." +msgstr "`std::error::Error` 特徵會自動衍生。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "The message from `#[error]` is used to derive the `Display` trait." +msgstr "`#[error]` 的訊息則用於衍生 `Display` 特徵。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "`anyhow`" +msgstr "`anyhow`" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"`anyhow::Error` is essentially a wrapper around `Box`. As such " +"it's again generally not a good choice for the public API of a library, but " +"is widely used in applications." +msgstr "" +"`anyhow::Error` 基本上是 `Box` 周遭的包裝函式。因此,通常也是不建" +"議程式庫的公用 API 使用,但可在應用程式中廣泛使用。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "`anyhow::Result` is a type alias for `Result`." +msgstr "`anyhow::Result` 是 `Result` 的型別別名。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"Actual error type inside of it can be extracted for examination if necessary." +msgstr "必要時,可以擷取其中的實際錯誤類型進行檢查。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"Functionality provided by `anyhow::Result` may be familiar to Go " +"developers, as it provides similar usage patterns and ergonomics to `(T, " +"error)` from Go." +msgstr "" +"Go 開發人員可能會覺得 `anyhow::Result` 提供的功能似曾相識,因為該功能提供" +"了與 Go 中的 `(T, error)` 類似的使用模式和人體工學。" + +#: src/error-handling/thiserror-and-anyhow.md +msgid "" +"`anyhow::Context` is a trait implemented for the standard `Result` and " +"`Option` types. `use anyhow::Context` is necessary to enable `.context()` " +"and `.with_context()` on those types." +msgstr "" +"`anyhow::Context` 是針對標準 `Result` 和 `Option` 型別實作的特徵。如要啟用這" +"些型別的 `.context()` 和 `.with_context()`,就必須使用 anyhow::Context。" + +#: src/error-handling/exercise.md +msgid "Exercise: Rewriting with Result" +msgstr "練習:根據結果重新編寫" + +#: src/error-handling/exercise.md +msgid "" +"The following implements a very simple parser for an expression language. " +"However, it handles errors by panicking. Rewrite it to instead use idiomatic " +"error handling and propagate errors to a return from `main`. Feel free to " +"use `thiserror` and `anyhow`." +msgstr "" +"以下程式碼實作一個非常簡單的運算式語言剖析器,但會藉由恐慌來處理錯誤。請重新" +"編寫,改用慣用的錯誤處理機制,並將錯誤傳播至 `main` 的回傳陳述式。您可以自由" +"使用 `thiserror` 和 `anyhow`。" + +#: src/error-handling/exercise.md +msgid "" +"HINT: start by fixing error handling in the `parse` function. Once that is " +"working correctly, update `Tokenizer` to implement " +"`Iterator>` and handle that in the parser." +msgstr "" +"提示:首先請修正 `parse` 函式中的錯誤處理機制。確認一切正常運作後,更新 " +"`Tokenizer` 即可實作 `Iterator>`,並在剖析" +"器中處理。" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "/// An arithmetic operator.\n" +msgstr "/// An arithmetic operator.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "/// A token in the expression language.\n" +msgstr "/// A token in the expression language.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "/// An expression in the expression language.\n" +msgstr "/// An expression in the expression language.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "/// A reference to a variable.\n" +msgstr "/// A reference to a variable.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "/// A literal number.\n" +msgstr "/// A literal number.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "/// A binary operation.\n" +msgstr "/// A binary operation.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "'z'" +msgstr "'z'" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "'_'" +msgstr "'_'" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "'+'" +msgstr "'+'" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "'-'" +msgstr "'-'" + +#: src/error-handling/exercise.md +msgid "\"Unexpected character {c}\"" +msgstr "\"Unexpected character {c}\"" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "\"Unexpected end of input\"" +msgstr "\"Unexpected end of input\"" + +#: src/error-handling/exercise.md +msgid "\"Invalid 32-bit integer'\"" +msgstr "\"Invalid 32-bit integer'\"" + +#: src/error-handling/exercise.md +msgid "\"Unexpected token {tok:?}\"" +msgstr "\"Unexpected token {tok:?}\"" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "// Look ahead to parse a binary operation if present.\n" +msgstr "// Look ahead to parse a binary operation if present.\n" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "\"10+foo+20-30\"" +msgstr "\"10+foo+20-30\"" + +#: src/error-handling/exercise.md src/error-handling/solution.md +msgid "\"{expr:?}\"" +msgstr "\"{expr:?}\"" + +#: src/error-handling/solution.md +msgid "\"Unexpected character '{0}' in input\"" +msgstr "\"Unexpected character '{0}' in input\"" + +#: src/error-handling/solution.md +msgid "\"Tokenizer error: {0}\"" +msgstr "\"Tokenizer error: {0}\"" + +#: src/error-handling/solution.md +msgid "\"Unexpected token {0:?}\"" +msgstr "\"Unexpected token {0:?}\"" + +#: src/error-handling/solution.md +msgid "\"Invalid number\"" +msgstr "\"Invalid number\"" + +#: src/unsafe-rust.md +msgid "[Unsafe](./unsafe-rust/unsafe.md) (5 minutes)" +msgstr "[不安全](./unsafe-rust/unsafe.md) (5 分鐘)" + +#: src/unsafe-rust.md +msgid "" +"[Dereferencing Raw Pointers](./unsafe-rust/dereferencing.md) (10 minutes)" +msgstr "[將原始指標解除參照](./unsafe-rust/dereferencing.md) (10 分鐘)" + +#: src/unsafe-rust.md +msgid "[Mutable Static Variables](./unsafe-rust/mutable-static.md) (5 minutes)" +msgstr "[可變動的靜態變數](./unsafe-rust/mutable-static.md) (5 分鐘)" + +#: src/unsafe-rust.md +msgid "[Unions](./unsafe-rust/unions.md) (5 minutes)" +msgstr "[聯集](./unsafe-rust/unions.md) (5 minutes)" + +#: src/unsafe-rust.md +msgid "[Unsafe Functions](./unsafe-rust/unsafe-functions.md) (5 minutes)" +msgstr "[不安全的函式](./unsafe-rust/unsafe-functions.md) (5 分鐘)" + +#: src/unsafe-rust.md +msgid "[Unsafe Traits](./unsafe-rust/unsafe-traits.md) (5 minutes)" +msgstr "[不安全的特徵](./unsafe-rust/unsafe-traits.md) (5 分鐘)" + +#: src/unsafe-rust.md +msgid "[Exercise: FFI Wrapper](./unsafe-rust/exercise.md) (30 minutes)" +msgstr "[練習:FFI 包裝函式](./unsafe-rust/exercise.md) (30 分鐘)" + +#: src/unsafe-rust.md +msgid "This segment should take about 1 hour and 5 minutes" +msgstr "講解這個主題大約需要 1 小時 5 分鐘" + +#: src/unsafe-rust/unsafe.md msgid "The Rust language has two parts:" msgstr "Rust 語言包含兩個部分:" -#: src/unsafe.md:5 +#: src/unsafe-rust/unsafe.md msgid "**Safe Rust:** memory safe, no undefined behavior possible." msgstr "\\*\\*安全的 Rust:\\*\\*可確保記憶體安全,無法觸發未定義的行為。" -#: src/unsafe.md:6 +#: src/unsafe-rust/unsafe.md msgid "" "**Unsafe Rust:** can trigger undefined behavior if preconditions are " "violated." msgstr "\\*\\*不安全的 Rust:\\*\\*如果違反先決條件,便可能觸發未定義的行為。" -#: src/unsafe.md:8 +#: src/unsafe-rust/unsafe.md +#, fuzzy msgid "" -"We will be seeing mostly safe Rust in this course, but it's important to " -"know what Unsafe Rust is." +"We saw mostly safe Rust in this course, but it's important to know what " +"Unsafe Rust is." msgstr "雖然本課程中出現的大多都是安全的 Rust,但瞭解不安全的 Rust 也很重要。" -#: src/unsafe.md:11 +#: src/unsafe-rust/unsafe.md msgid "" "Unsafe code is usually small and isolated, and its correctness should be " "carefully documented. It is usually wrapped in a safe abstraction layer." @@ -11562,31 +11213,31 @@ msgstr "" "不安全的程式碼通常都很簡短、受到隔離,而且封裝在安全的抽象層中。您應該仔細記" "錄這類程式碼的正確性。" -#: src/unsafe.md:14 +#: src/unsafe-rust/unsafe.md msgid "Unsafe Rust gives you access to five new capabilities:" msgstr "透過不安全的 Rust,可以使用五項新功能:" -#: src/unsafe.md:16 +#: src/unsafe-rust/unsafe.md msgid "Dereference raw pointers." msgstr "對裸指標解參考。" -#: src/unsafe.md:17 +#: src/unsafe-rust/unsafe.md msgid "Access or modify mutable static variables." msgstr "存取或修改可變的靜態變數。" -#: src/unsafe.md:18 +#: src/unsafe-rust/unsafe.md msgid "Access `union` fields." msgstr "存取 `union` 欄位。" -#: src/unsafe.md:19 +#: src/unsafe-rust/unsafe.md msgid "Call `unsafe` functions, including `extern` functions." msgstr "呼叫 `unsafe` 函式 (包括 `extern` 函式)。" -#: src/unsafe.md:20 +#: src/unsafe-rust/unsafe.md msgid "Implement `unsafe` traits." msgstr "實作 `unsafe` 特徵。" -#: src/unsafe.md:22 +#: src/unsafe-rust/unsafe.md msgid "" "We will briefly cover unsafe capabilities next. For full details, please see " "[Chapter 19.1 in the Rust Book](https://doc.rust-lang.org/book/ch19-01-" @@ -11596,10 +11247,11 @@ msgstr "" "(https://rust-lang.tw/book-tw/ch19-01-unsafe-rust.html),以及 [Rustonomicon]" "(https://doc.rust-lang.org/nomicon/)。" -#: src/unsafe.md:28 +#: src/unsafe-rust/unsafe.md +#, fuzzy msgid "" "Unsafe Rust does not mean the code is incorrect. It means that developers " -"have turned off the compiler safety features and have to write correct code " +"have turned off some compiler safety features and have to write correct code " "by themselves. It means the compiler no longer enforces Rust's memory-safety " "rules." msgstr "" @@ -11608,35 +11260,59 @@ msgstr "" "by themselves. It means the compiler no longer enforces Rust's memory-safety " "rules." -#: src/unsafe/raw-pointers.md:3 +#: src/unsafe-rust/dereferencing.md msgid "Creating pointers is safe, but dereferencing them requires `unsafe`:" msgstr "建立指標相當安全,不過對指標解參考就需要使用 `unsafe`:" -#: src/unsafe/raw-pointers.md:5 +#: src/unsafe-rust/dereferencing.md +msgid "\"careful!\"" +msgstr "\"careful!\"" + +#: src/unsafe-rust/dereferencing.md msgid "" -"```rust,editable\n" -"fn main() {\n" -" let mut num = 5;\n" -"\n" -" let r1 = &mut num as *mut i32;\n" -" let r2 = r1 as *const i32;\n" -"\n" -" // Safe because r1 and r2 were obtained from references and so are\n" +"// Safe because r1 and r2 were obtained from references and so are\n" " // guaranteed to be non-null and properly aligned, the objects " "underlying\n" " // the references from which they were obtained are live throughout the\n" " // whole unsafe block, and they are not accessed either through the\n" " // references or concurrently through any other pointers.\n" -" unsafe {\n" -" println!(\"r1 is: {}\", *r1);\n" -" *r1 = 10;\n" -" println!(\"r2 is: {}\", *r2);\n" -" }\n" -"}\n" -"```" msgstr "" +"// Safe because r1 and r2 were obtained from references and so are\n" +" // guaranteed to be non-null and properly aligned, the objects " +"underlying\n" +" // the references from which they were obtained are live throughout the\n" +" // whole unsafe block, and they are not accessed either through the\n" +" // references or concurrently through any other pointers.\n" -#: src/unsafe/raw-pointers.md:27 +#: src/unsafe-rust/dereferencing.md +msgid "\"r1 is: {}\"" +msgstr "\"r1 is: {}\"" + +#: src/unsafe-rust/dereferencing.md +msgid "\"uhoh\"" +msgstr "\"uhoh\"" + +#: src/unsafe-rust/dereferencing.md +msgid "\"r2 is: {}\"" +msgstr "\"r2 is: {}\"" + +#: src/unsafe-rust/dereferencing.md +msgid "" +"// NOT SAFE. DO NOT DO THIS.\n" +" /*\n" +" let r3: &String = unsafe { &*r1 };\n" +" drop(s);\n" +" println!(\"r3 is: {}\", *r3);\n" +" */" +msgstr "" +"// NOT SAFE. DO NOT DO THIS.\n" +" /*\n" +" let r3: &String = unsafe { &*r1 };\n" +" drop(s);\n" +" println!(\"r3 is: {}\", *r3);\n" +" */" + +#: src/unsafe-rust/dereferencing.md msgid "" "It is good practice (and required by the Android Rust style guide) to write " "a comment for each `unsafe` block explaining how the code inside it " @@ -11646,7 +11322,7 @@ msgstr "" "a comment for each `unsafe` block explaining how the code inside it " "satisfies the safety requirements of the unsafe operations it is doing." -#: src/unsafe/raw-pointers.md:31 +#: src/unsafe-rust/dereferencing.md msgid "" "In the case of pointer dereferences, this means that the pointers must be " "[_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety), i.e.:" @@ -11654,11 +11330,11 @@ msgstr "" "In the case of pointer dereferences, this means that the pointers must be " "[_valid_](https://doc.rust-lang.org/std/ptr/index.html#safety), i.e.:" -#: src/unsafe/raw-pointers.md:34 +#: src/unsafe-rust/dereferencing.md msgid "The pointer must be non-null." msgstr "The pointer must be non-null." -#: src/unsafe/raw-pointers.md:35 +#: src/unsafe-rust/dereferencing.md msgid "" "The pointer must be _dereferenceable_ (within the bounds of a single " "allocated object)." @@ -11666,15 +11342,15 @@ msgstr "" "The pointer must be _dereferenceable_ (within the bounds of a single " "allocated object)." -#: src/unsafe/raw-pointers.md:36 +#: src/unsafe-rust/dereferencing.md msgid "The object must not have been deallocated." msgstr "The object must not have been deallocated." -#: src/unsafe/raw-pointers.md:37 +#: src/unsafe-rust/dereferencing.md msgid "There must not be concurrent accesses to the same location." msgstr "There must not be concurrent accesses to the same location." -#: src/unsafe/raw-pointers.md:38 +#: src/unsafe-rust/dereferencing.md msgid "" "If the pointer was obtained by casting a reference, the underlying object " "must be live and no reference may be used to access the memory." @@ -11682,49 +11358,55 @@ msgstr "" "If the pointer was obtained by casting a reference, the underlying object " "must be live and no reference may be used to access the memory." -#: src/unsafe/raw-pointers.md:41 +#: src/unsafe-rust/dereferencing.md msgid "In most cases the pointer must also be properly aligned." msgstr "In most cases the pointer must also be properly aligned." -#: src/unsafe/mutable-static-variables.md:3 +#: src/unsafe-rust/dereferencing.md +msgid "" +"The \"NOT SAFE\" section gives an example of a common kind of UB bug: `*r1` " +"has the `'static` lifetime, so `r3` has type `&'static String`, and thus " +"outlives `s`. Creating a reference from a pointer requires _great care_." +msgstr "" +"「NOT SAFE」部分提供了常見的 UB 錯誤示例:`*r1` 具有 `'static` 生命週期,因" +"此 `r3` 具有 `&'static String` 這個型別,從而會超過 `s`。從指標建立參照需要" +"「格外謹慎」__。" + +#: src/unsafe-rust/mutable-static.md msgid "It is safe to read an immutable static variable:" msgstr "您可以放心讀取不可變的靜態變數:" -#: src/unsafe/mutable-static-variables.md:5 -msgid "" -"```rust,editable\n" -"static HELLO_WORLD: &str = \"Hello, world!\";\n" -"\n" -"fn main() {\n" -" println!(\"HELLO_WORLD: {HELLO_WORLD}\");\n" -"}\n" -"```" -msgstr "" +#: src/unsafe-rust/mutable-static.md +#, fuzzy +msgid "\"Hello, world!\"" +msgstr "Hello World!" -#: src/unsafe/mutable-static-variables.md:13 +#: src/unsafe-rust/mutable-static.md +msgid "\"HELLO_WORLD: {HELLO_WORLD}\"" +msgstr "\"HELLO_WORLD: {HELLO_WORLD}\"" + +#: src/unsafe-rust/mutable-static.md msgid "" "However, since data races can occur, it is unsafe to read and write mutable " "static variables:" msgstr "不過,讀取並寫入可變的靜態變數並不安全,因為可能發生資料競爭:" -#: src/unsafe/mutable-static-variables.md:16 -msgid "" -"```rust,editable\n" -"static mut COUNTER: u32 = 0;\n" -"\n" -"fn add_to_counter(inc: u32) {\n" -" unsafe { COUNTER += inc; } // Potential data race!\n" -"}\n" -"\n" -"fn main() {\n" -" add_to_counter(42);\n" -"\n" -" unsafe { println!(\"COUNTER: {COUNTER}\"); } // Potential data race!\n" -"}\n" -"```" -msgstr "" +#: src/unsafe-rust/mutable-static.md +msgid "\"COUNTER: {COUNTER}\"" +msgstr "\"COUNTER: {COUNTER}\"" -#: src/unsafe/mutable-static-variables.md:32 +#: src/unsafe-rust/mutable-static.md +msgid "" +"The program here is safe because it is single-threaded. However, the Rust " +"compiler is conservative and will assume the worst. Try removing the " +"`unsafe` and see how the compiler explains that it is undefined behavior to " +"mutate a static from multiple threads." +msgstr "" +"這裡的程式採用單一執行緒,因此安全無虞。不過,Rust 編譯器較為保守,會設想最糟" +"的情況。請嘗試移除 `unsafe`,看看編譯器如何解釋為什麼從多個執行緒變更 " +"static,屬於未定義的行為。" + +#: src/unsafe-rust/mutable-static.md msgid "" "Using a mutable static is generally a bad idea, but there are some cases " "where it might make sense in low-level `no_std` code, such as implementing a " @@ -11734,28 +11416,24 @@ msgstr "" "where it might make sense in low-level `no_std` code, such as implementing a " "heap allocator or working with some C APIs." -#: src/unsafe/unions.md:3 +#: src/unsafe-rust/unions.md msgid "Unions are like enums, but you need to track the active field yourself:" msgstr "聯合體和列舉很像,但您需要自行追蹤可用欄位:" -#: src/unsafe/unions.md:5 -msgid "" -"```rust,editable\n" -"#[repr(C)]\n" -"union MyUnion {\n" -" i: u8,\n" -" b: bool,\n" -"}\n" -"\n" -"fn main() {\n" -" let u = MyUnion { i: 42 };\n" -" println!(\"int: {}\", unsafe { u.i });\n" -" println!(\"bool: {}\", unsafe { u.b }); // Undefined behavior!\n" -"}\n" -"```" -msgstr "" +#: src/unsafe-rust/unions.md +msgid "\"int: {}\"" +msgstr "\"int: {}\"" -#: src/unsafe/unions.md:21 +#: src/unsafe-rust/unions.md +msgid "\"bool: {}\"" +msgstr "\"bool: {}\"" + +#: src/unsafe-rust/unions.md +#, fuzzy +msgid "// Undefined behavior!\n" +msgstr "在執行階段不會產生未定義的行為,好處如下:" + +#: src/unsafe-rust/unions.md msgid "" "Unions are very rarely needed in Rust as you can usually use an enum. They " "are occasionally needed for interacting with C library APIs." @@ -11763,7 +11441,7 @@ msgstr "" "Unions are very rarely needed in Rust as you can usually use an enum. They " "are occasionally needed for interacting with C library APIs." -#: src/unsafe/unions.md:24 +#: src/unsafe-rust/unions.md msgid "" "If you just want to reinterpret bytes as a different type, you probably want " "[`std::mem::transmute`](https://doc.rust-lang.org/stable/std/mem/fn." @@ -11775,7 +11453,11 @@ msgstr "" "transmute.html) or a safe wrapper such as the [`zerocopy`](https://crates.io/" "crates/zerocopy) crate." -#: src/unsafe/calling-unsafe-functions.md:3 +#: src/unsafe-rust/unsafe-functions.md +msgid "Calling Unsafe Functions" +msgstr "呼叫不安全的函式" + +#: src/unsafe-rust/unsafe-functions.md msgid "" "A function or method can be marked `unsafe` if it has extra preconditions " "you must uphold to avoid undefined behaviour:" @@ -11783,126 +11465,105 @@ msgstr "" "如果函式或方法具有額外先決條件,而您必須遵循這些條件才能避免未定義的行為,那" "麼就可以將該函式或方法標示為 `unsafe`:" -#: src/unsafe/calling-unsafe-functions.md:6 -msgid "" -"```rust,editable\n" -"fn main() {\n" -" let emojis = \"🗻∈🌏\";\n" -"\n" -" // Safe because the indices are in the correct order, within the bounds " -"of\n" -" // the string slice, and lie on UTF-8 sequence boundaries.\n" -" unsafe {\n" -" println!(\"emoji: {}\", emojis.get_unchecked(0..4));\n" -" println!(\"emoji: {}\", emojis.get_unchecked(4..7));\n" -" println!(\"emoji: {}\", emojis.get_unchecked(7..11));\n" -" }\n" -"\n" -" println!(\"char count: {}\", count_chars(unsafe { emojis." -"get_unchecked(0..7) }));\n" -"\n" -" // Not upholding the UTF-8 encoding requirement breaks memory safety!\n" -" // println!(\"emoji: {}\", unsafe { emojis.get_unchecked(0..3) });\n" -" // println!(\"char count: {}\", count_chars(unsafe { emojis." -"get_unchecked(0..3) }));\n" -"}\n" -"\n" -"fn count_chars(s: &str) -> usize {\n" -" s.chars().map(|_| 1).sum()\n" -"}\n" -"```" -msgstr "" +#: src/unsafe-rust/unsafe-functions.md src/unsafe-rust/exercise.md +#: src/unsafe-rust/solution.md src/android/interoperability/with-c.md +#: src/android/interoperability/with-c/rust.md +#: src/android/interoperability/cpp/cpp-bridge.md +#: src/exercises/chromium/build-rules.md src/bare-metal/aps/inline-assembly.md +#: src/bare-metal/aps/better-uart/using.md src/bare-metal/aps/logging/using.md +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"C\"" +msgstr "\"C\"" -#: src/unsafe/writing-unsafe-functions.md:3 +#: src/unsafe-rust/unsafe-functions.md +msgid "\"🗻∈🌏\"" +msgstr "\"🗻∈🌏\"" + +#: src/unsafe-rust/unsafe-functions.md +msgid "" +"// Safe because the indices are in the correct order, within the bounds of\n" +" // the string slice, and lie on UTF-8 sequence boundaries.\n" +msgstr "" +"// Safe because the indices are in the correct order, within the bounds of\n" +" // the string slice, and lie on UTF-8 sequence boundaries.\n" + +#: src/unsafe-rust/unsafe-functions.md +msgid "\"emoji: {}\"" +msgstr "\"emoji: {}\"" + +#: src/unsafe-rust/unsafe-functions.md +msgid "\"char count: {}\"" +msgstr "\"char count: {}\"" + +#: src/unsafe-rust/unsafe-functions.md +#, fuzzy +msgid "// Undefined behavior if abs misbehaves.\n" +msgstr "在執行階段不會產生未定義的行為,好處如下:" + +#: src/unsafe-rust/unsafe-functions.md +msgid "\"Absolute value of -3 according to C: {}\"" +msgstr "\"Absolute value of -3 according to C: {}\"" + +#: src/unsafe-rust/unsafe-functions.md +msgid "" +"// Not upholding the UTF-8 encoding requirement breaks memory safety!\n" +" // println!(\"emoji: {}\", unsafe { emojis.get_unchecked(0..3) });\n" +" // println!(\"char count: {}\", count_chars(unsafe {\n" +" // emojis.get_unchecked(0..3) }));\n" +msgstr "" +"// Not upholding the UTF-8 encoding requirement breaks memory safety!\n" +" // println!(\"emoji: {}\", unsafe { emojis.get_unchecked(0..3) });\n" +" // println!(\"char count: {}\", count_chars(unsafe {\n" +" // emojis.get_unchecked(0..3) }));\n" + +#: src/unsafe-rust/unsafe-functions.md +msgid "Writing Unsafe Functions" +msgstr "編寫不安全的函式" + +#: src/unsafe-rust/unsafe-functions.md msgid "" "You can mark your own functions as `unsafe` if they require particular " "conditions to avoid undefined behaviour." msgstr "" "如果您的函式必須滿足特定條件才能避免未定義的行為,您可以將其標示為 `unsafe`。" -#: src/unsafe/writing-unsafe-functions.md:6 +#: src/unsafe-rust/unsafe-functions.md msgid "" -"```rust,editable\n" "/// Swaps the values pointed to by the given pointers.\n" "///\n" "/// # Safety\n" "///\n" "/// The pointers must be valid and properly aligned.\n" -"unsafe fn swap(a: *mut u8, b: *mut u8) {\n" -" let temp = *a;\n" -" *a = *b;\n" -" *b = temp;\n" -"}\n" -"\n" -"fn main() {\n" -" let mut a = 42;\n" -" let mut b = 66;\n" -"\n" -" // Safe because ...\n" -" unsafe {\n" -" swap(&mut a, &mut b);\n" -" }\n" -"\n" -" println!(\"a = {}, b = {}\", a, b);\n" -"}\n" -"```" msgstr "" +"/// Swaps the values pointed to by the given pointers.\n" +"///\n" +"/// # Safety\n" +"///\n" +"/// The pointers must be valid and properly aligned.\n" -#: src/unsafe/writing-unsafe-functions.md:33 +#: src/unsafe-rust/unsafe-functions.md +msgid "// Safe because ...\n" +msgstr "// Safe because ...\n" + +#: src/unsafe-rust/unsafe-functions.md +msgid "\"a = {}, b = {}\"" +msgstr "\"a = {}, b = {}\"" + +#: src/unsafe-rust/unsafe-functions.md +#, fuzzy msgid "" -"We wouldn't actually use pointers for this because it can be done safely " -"with references." -msgstr "" -"We wouldn't actually use pointers for this because it can be done safely " -"with references." - -#: src/unsafe/writing-unsafe-functions.md:35 -msgid "" -"Note that unsafe code is allowed within an unsafe function without an " -"`unsafe` block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. " -"Try adding it and see what happens." -msgstr "" -"Note that unsafe code is allowed within an unsafe function without an " -"`unsafe` block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. " -"Try adding it and see what happens." - -#: src/unsafe/extern-functions.md:1 -msgid "Calling External Code" -msgstr "呼叫外部程式碼" - -#: src/unsafe/extern-functions.md:3 -msgid "" -"Functions from other languages might violate the guarantees of Rust. Calling " -"them is thus unsafe:" -msgstr "其他語言的函式可能會違反 Rust 保證,因此呼叫這類函式並不安全:" - -#: src/unsafe/extern-functions.md:6 -msgid "" -"```rust,editable\n" -"extern \"C\" {\n" -" fn abs(input: i32) -> i32;\n" -"}\n" -"\n" -"fn main() {\n" -" unsafe {\n" -" // Undefined behavior if abs misbehaves.\n" -" println!(\"Absolute value of -3 according to C: {}\", abs(-3));\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/unsafe/extern-functions.md:21 -msgid "" -"This is usually only a problem for extern functions which do things with " -"pointers which might violate Rust's memory model, but in general any C " -"function might have undefined behaviour under any arbitrary circumstances." +"`get_unchecked`, like most `_unchecked` functions, is unsafe, because it can " +"create UB if the range is incorrect. `abs` is incorrect for a different " +"reason: it is an external function (FFI). Calling external functions is " +"usually only a problem when those functions do things with pointers which " +"might violate Rust's memory model, but in general any C function might have " +"undefined behaviour under any arbitrary circumstances." msgstr "" "This is usually only a problem for extern functions which do things with " "pointers which might violate Rust's memory model, but in general any C " "function might have undefined behaviour under any arbitrary circumstances." -#: src/unsafe/extern-functions.md:25 +#: src/unsafe-rust/unsafe-functions.md msgid "" "The `\"C\"` in this example is the ABI; [other ABIs are available too]" "(https://doc.rust-lang.org/reference/items/external-blocks.html)." @@ -11910,7 +11571,32 @@ msgstr "" "此例中的 `\"C\"` 為 ABI;[您也可以使用其他 ABI](https://doc.rust-lang.org/" "reference/items/external-blocks.html)。" -#: src/unsafe/unsafe-traits.md:3 +#: src/unsafe-rust/unsafe-functions.md +#, fuzzy +msgid "" +"We wouldn't actually use pointers for a `swap` function - it can be done " +"safely with references." +msgstr "" +"We wouldn't actually use pointers for this because it can be done safely " +"with references." + +#: src/unsafe-rust/unsafe-functions.md +#, fuzzy +msgid "" +"Note that unsafe code is allowed within an unsafe function without an " +"`unsafe` block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. " +"Try adding it and see what happens. This will likely change in a future Rust " +"edition." +msgstr "" +"Note that unsafe code is allowed within an unsafe function without an " +"`unsafe` block. We can prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. " +"Try adding it and see what happens." + +#: src/unsafe-rust/unsafe-traits.md +msgid "Implementing Unsafe Traits" +msgstr "實作不安全的特徵" + +#: src/unsafe-rust/unsafe-traits.md msgid "" "Like with functions, you can mark a trait as `unsafe` if the implementation " "must guarantee particular conditions to avoid undefined behaviour." @@ -11918,7 +11604,7 @@ msgstr "" "與函式類似,如果實作程序必須保證符合特定條件才能避免未定義的行為,您可以將特" "徵標示為 `unsafe`。" -#: src/unsafe/unsafe-traits.md:6 +#: src/unsafe-rust/unsafe-traits.md msgid "" "For example, the `zerocopy` crate has an unsafe trait that looks [something " "like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html):" @@ -11926,30 +11612,21 @@ msgstr "" "舉例來說,`zerocopy` crate 就具有不安全的特徵,如[這個頁面](https://docs.rs/" "zerocopy/latest/zerocopy/trait.AsBytes.html)所示:" -#: src/unsafe/unsafe-traits.md:9 +#: src/unsafe-rust/unsafe-traits.md msgid "" -"```rust,editable\n" -"use std::mem::size_of_val;\n" -"use std::slice;\n" -"\n" "/// ...\n" "/// # Safety\n" "/// The type must have a defined representation and no padding.\n" -"pub unsafe trait AsBytes {\n" -" fn as_bytes(&self) -> &[u8] {\n" -" unsafe {\n" -" slice::from_raw_parts(self as *const Self as *const u8, " -"size_of_val(self))\n" -" }\n" -" }\n" -"}\n" -"\n" -"// Safe because u32 has a defined representation and no padding.\n" -"unsafe impl AsBytes for u32 {}\n" -"```" msgstr "" +"/// ...\n" +"/// # Safety\n" +"/// The type must have a defined representation and no padding.\n" -#: src/unsafe/unsafe-traits.md:30 +#: src/unsafe-rust/unsafe-traits.md +msgid "// Safe because u32 has a defined representation and no padding.\n" +msgstr "// Safe because u32 has a defined representation and no padding.\n" + +#: src/unsafe-rust/unsafe-traits.md msgid "" "There should be a `# Safety` section on the Rustdoc for the trait explaining " "the requirements for the trait to be safely implemented." @@ -11957,7 +11634,7 @@ msgstr "" "There should be a `# Safety` section on the Rustdoc for the trait explaining " "the requirements for the trait to be safely implemented." -#: src/unsafe/unsafe-traits.md:33 +#: src/unsafe-rust/unsafe-traits.md msgid "" "The actual safety section for `AsBytes` is rather longer and more " "complicated." @@ -11965,51 +11642,42 @@ msgstr "" "The actual safety section for `AsBytes` is rather longer and more " "complicated." -#: src/unsafe/unsafe-traits.md:35 +#: src/unsafe-rust/unsafe-traits.md msgid "The built-in `Send` and `Sync` traits are unsafe." msgstr "The built-in `Send` and `Sync` traits are unsafe." -#: src/exercises/day-3/afternoon.md:1 -msgid "Day 3: Afternoon Exercises" -msgstr "第 3 天:下午練習" +#: src/unsafe-rust/exercise.md +msgid "Safe FFI Wrapper" +msgstr "安全的 FFI 包裝函式" -#: src/exercises/day-3/afternoon.md:3 -msgid "Let us build a safe wrapper for reading directory content!" -msgstr "我們來建構用於讀取目錄內容的安全包裝函式吧!" - -#: src/exercises/day-3/afternoon.md:14 -msgid "" -"After looking at the exercise, you can look at the [solution](solutions-" -"afternoon.md) provided." -msgstr "完成練習後,您可以看看我們提供的[解決方案](solutions-afternoon.md)。" - -#: src/exercises/day-3/safe-ffi-wrapper.md:3 +#: src/unsafe-rust/exercise.md +#, fuzzy msgid "" "Rust has great support for calling functions through a _foreign function " "interface_ (FFI). We will use this to build a safe wrapper for the `libc` " -"functions you would use from C to read the filenames of a directory." +"functions you would use from C to read the names of files in a directory." msgstr "" "Rust 對透過「外部函式介面」__(FFI) 呼叫函式的做法提供強大支援。我們會利用這點" "來為 `libc` 函式建立安全的包裝函式,這是您在 C 語言中用來讀取目錄檔案名稱的函" "式。" -#: src/exercises/day-3/safe-ffi-wrapper.md:7 +#: src/unsafe-rust/exercise.md msgid "You will want to consult the manual pages:" msgstr "建議您參閱以下手冊頁面:" -#: src/exercises/day-3/safe-ffi-wrapper.md:9 +#: src/unsafe-rust/exercise.md msgid "[`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html)" msgstr "[`opendir(3)`](https://man7.org/linux/man-pages/man3/opendir.3.html)" -#: src/exercises/day-3/safe-ffi-wrapper.md:10 +#: src/unsafe-rust/exercise.md msgid "[`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html)" msgstr "[`readdir(3)`](https://man7.org/linux/man-pages/man3/readdir.3.html)" -#: src/exercises/day-3/safe-ffi-wrapper.md:11 +#: src/unsafe-rust/exercise.md msgid "[`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html)" msgstr "[`closedir(3)`](https://man7.org/linux/man-pages/man3/closedir.3.html)" -#: src/exercises/day-3/safe-ffi-wrapper.md:13 +#: src/unsafe-rust/exercise.md msgid "" "You will also want to browse the [`std::ffi`](https://doc.rust-lang.org/std/" "ffi/) module. There you find a number of string types which you need for the " @@ -12018,15 +11686,15 @@ msgstr "" "建議您一併瀏覽 [`std::ffi`](https://doc.rust-lang.org/std/ffi/) 模組。其中會" "有練習需用到的幾個字串型別:" -#: src/exercises/day-3/safe-ffi-wrapper.md:16 +#: src/unsafe-rust/exercise.md msgid "Encoding" msgstr "編碼" -#: src/exercises/day-3/safe-ffi-wrapper.md:16 +#: src/unsafe-rust/exercise.md msgid "Use" msgstr "使用" -#: src/exercises/day-3/safe-ffi-wrapper.md:18 +#: src/unsafe-rust/exercise.md msgid "" "[`str`](https://doc.rust-lang.org/std/primitive.str.html) and [`String`]" "(https://doc.rust-lang.org/std/string/struct.String.html)" @@ -12034,15 +11702,15 @@ msgstr "" "[`str`](https://doc.rust-lang.org/std/primitive.str.html) 和 [`String`]" "(https://doc.rust-lang.org/std/string/struct.String.html)" -#: src/exercises/day-3/safe-ffi-wrapper.md:18 +#: src/unsafe-rust/exercise.md msgid "UTF-8" msgstr "UTF-8" -#: src/exercises/day-3/safe-ffi-wrapper.md:18 +#: src/unsafe-rust/exercise.md msgid "Text processing in Rust" msgstr "在 Rust 中處理文字" -#: src/exercises/day-3/safe-ffi-wrapper.md:19 +#: src/unsafe-rust/exercise.md msgid "" "[`CStr`](https://doc.rust-lang.org/std/ffi/struct.CStr.html) and [`CString`]" "(https://doc.rust-lang.org/std/ffi/struct.CString.html)" @@ -12050,15 +11718,15 @@ msgstr "" "[`CStr`](https://doc.rust-lang.org/std/ffi/struct.CStr.html) 和 [`CString`]" "(https://doc.rust-lang.org/std/ffi/struct.CString.html)" -#: src/exercises/day-3/safe-ffi-wrapper.md:19 +#: src/unsafe-rust/exercise.md msgid "NUL-terminated" msgstr "空字串結尾" -#: src/exercises/day-3/safe-ffi-wrapper.md:19 +#: src/unsafe-rust/exercise.md msgid "Communicating with C functions" msgstr "與 C 函式通訊" -#: src/exercises/day-3/safe-ffi-wrapper.md:20 +#: src/unsafe-rust/exercise.md msgid "" "[`OsStr`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html) and " "[`OsString`](https://doc.rust-lang.org/std/ffi/struct.OsString.html)" @@ -12066,41 +11734,42 @@ msgstr "" "[`OsStr`](https://doc.rust-lang.org/std/ffi/struct.OsStr.html) 和 " "[`OsString`](https://doc.rust-lang.org/std/ffi/struct.OsString.html)" -#: src/exercises/day-3/safe-ffi-wrapper.md:20 +#: src/unsafe-rust/exercise.md msgid "OS-specific" msgstr "特定 OS" -#: src/exercises/day-3/safe-ffi-wrapper.md:20 +#: src/unsafe-rust/exercise.md msgid "Communicating with the OS" msgstr "與 OS 通訊" -#: src/exercises/day-3/safe-ffi-wrapper.md:22 +#: src/unsafe-rust/exercise.md msgid "You will convert between all these types:" msgstr "您將在以下所有型別之間轉換:" -#: src/exercises/day-3/safe-ffi-wrapper.md:24 +#: src/unsafe-rust/exercise.md msgid "" "`&str` to `CString`: you need to allocate space for a trailing `\\0` " "character," msgstr "`&str` 到 `CString`:您需要為結尾的 `\\0` 字元分配空間。" -#: src/exercises/day-3/safe-ffi-wrapper.md:25 +#: src/unsafe-rust/exercise.md msgid "`CString` to `*const i8`: you need a pointer to call C functions," msgstr "`CString` 到 `*const i8`:您需要指標才能呼叫 C 函式。" -#: src/exercises/day-3/safe-ffi-wrapper.md:26 +#: src/unsafe-rust/exercise.md msgid "" "`*const i8` to `&CStr`: you need something which can find the trailing `\\0` " "character," msgstr "`*const i8` 到 `&CStr`:您需要一些可以找到結尾 `\\0` 字元的內容。" -#: src/exercises/day-3/safe-ffi-wrapper.md:27 +#: src/unsafe-rust/exercise.md +#, fuzzy msgid "" "`&CStr` to `&[u8]`: a slice of bytes is the universal interface for \"some " -"unknow data\"," +"unknown data\"," msgstr "`&CStr` 到 `&[u8]`:位元組切片是「某些未知資料」的通用介面。" -#: src/exercises/day-3/safe-ffi-wrapper.md:28 +#: src/unsafe-rust/exercise.md msgid "" "`&[u8]` to `&OsStr`: `&OsStr` is a step towards `OsString`, use [`OsStrExt`]" "(https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) to create it," @@ -12108,7 +11777,7 @@ msgstr "" "`&[u8]` 到 `&OsStr`:`&OsStr` 是通往 `OsString` 的一步,請以 [`OsStrExt`]" "(https://doc.rust-lang.org/std/os/unix/ffi/trait.OsStrExt.html) 建立。" -#: src/exercises/day-3/safe-ffi-wrapper.md:31 +#: src/unsafe-rust/exercise.md msgid "" "`&OsStr` to `OsString`: you need to clone the data in `&OsStr` to be able to " "return it and call `readdir` again." @@ -12116,7 +11785,7 @@ msgstr "" "`&OsStr` 到 `OsString`:您需複製 `&OsStr` 中的資料,才能傳回資料並再次呼叫 " "`readdir`。" -#: src/exercises/day-3/safe-ffi-wrapper.md:34 +#: src/unsafe-rust/exercise.md msgid "" "The [Nomicon](https://doc.rust-lang.org/nomicon/ffi.html) also has a very " "useful chapter about FFI." @@ -12124,1341 +11793,5007 @@ msgstr "" "[Nomicon](https://doc.rust-lang.org/nomicon/ffi.html) 也有關於 FFI 的實用章節" "可供參閱。" -#: src/exercises/day-3/safe-ffi-wrapper.md:45 +#: src/unsafe-rust/exercise.md msgid "" "Copy the code below to and fill in the missing " "functions and methods:" msgstr "" "請將以下程式碼複製到 ,並填入缺少的函式和方法:" -#: src/exercises/day-3/safe-ffi-wrapper.md:48 +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "\"macos\"" +msgstr "\"macos\"" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "// Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" +msgstr "// Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md msgid "" -"```rust,should_panic\n" -"// TODO: remove this when you're done with your implementation.\n" -"#![allow(unused_imports, unused_variables, dead_code)]\n" -"\n" -"mod ffi {\n" -" use std::os::raw::{c_char, c_int};\n" -" #[cfg(not(target_os = \"macos\"))]\n" -" use std::os::raw::{c_long, c_ulong, c_ushort};\n" -"\n" -" // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" -" #[repr(C)]\n" -" pub struct DIR {\n" -" _data: [u8; 0],\n" -" _marker: core::marker::PhantomData<(*mut u8, core::marker::" -"PhantomPinned)>,\n" -" }\n" -"\n" -" // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-" -"gnu.\n" -" #[cfg(not(target_os = \"macos\"))]\n" -" #[repr(C)]\n" -" pub struct dirent {\n" -" pub d_ino: c_long,\n" -" pub d_off: c_ulong,\n" -" pub d_reclen: c_ushort,\n" -" pub d_type: c_char,\n" -" pub d_name: [c_char; 256],\n" -" }\n" -"\n" -" // Layout as per man entry for dirent\n" -" #[cfg(target_os = \"macos\")]\n" -" #[repr(C)]\n" -" pub struct dirent {\n" -" pub d_ino: u64,\n" -" pub d_seekoff: u64,\n" -" pub d_reclen: u16,\n" -" pub d_namlen: u16,\n" -" pub d_type: u8,\n" -" pub d_name: [c_char; 1024],\n" -" }\n" -"\n" -" extern \"C\" {\n" -" pub fn opendir(s: *const c_char) -> *mut DIR;\n" -" pub fn readdir(s: *mut DIR) -> *const dirent;\n" -" pub fn closedir(s: *mut DIR) -> c_int;\n" -" }\n" -"}\n" -"\n" -"use std::ffi::{CStr, CString, OsStr, OsString};\n" -"use std::os::unix::ffi::OsStrExt;\n" -"\n" -"#[derive(Debug)]\n" -"struct DirectoryIterator {\n" -" path: CString,\n" -" dir: *mut ffi::DIR,\n" -"}\n" -"\n" -"impl DirectoryIterator {\n" -" fn new(path: &str) -> Result {\n" -" // Call opendir and return a Ok value if that worked,\n" +"// Layout according to the Linux man page for readdir(3), where ino_t and\n" +" // off_t are resolved according to the definitions in\n" +" // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.\n" +msgstr "" +"// Layout according to the Linux man page for readdir(3), where ino_t and\n" +" // off_t are resolved according to the definitions in\n" +" // /usr/include/x86_64-linux-gnu/{sys/types.h, bits/typesizes.h}.\n" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "// Layout according to the macOS man page for dir(5).\n" +msgstr "// Layout according to the macOS man page for dir(5).\n" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "\"x86_64\"" +msgstr "\"x86_64\"" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "" +"// See https://github.com/rust-lang/libc/issues/414 and the section on\n" +" // _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).\n" +" //\n" +" // \"Platforms that existed before these updates were available\" " +"refers\n" +" // to macOS (as opposed to iOS / wearOS / etc.) on Intel and " +"PowerPC.\n" +msgstr "" +"// See https://github.com/rust-lang/libc/issues/414 and the section on\n" +" // _DARWIN_FEATURE_64_BIT_INODE in the macOS man page for stat(2).\n" +" //\n" +" // \"Platforms that existed before these updates were available\" " +"refers\n" +" // to macOS (as opposed to iOS / wearOS / etc.) on Intel and " +"PowerPC.\n" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "\"readdir$INODE64\"" +msgstr "\"readdir$INODE64\"" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "" +"// Call opendir and return a Ok value if that worked,\n" " // otherwise return Err with a message.\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"impl Iterator for DirectoryIterator {\n" -" type Item = OsString;\n" -" fn next(&mut self) -> Option {\n" -" // Keep calling readdir until we get a NULL pointer back.\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"impl Drop for DirectoryIterator {\n" -" fn drop(&mut self) {\n" -" // Call closedir as needed.\n" -" unimplemented!()\n" -" }\n" -"}\n" -"\n" -"fn main() -> Result<(), String> {\n" -" let iter = DirectoryIterator::new(\".\")?;\n" -" println!(\"files: {:#?}\", iter.collect::>());\n" -" Ok(())\n" -"}\n" -"```" msgstr "" +"// Call opendir and return a Ok value if that worked,\n" +" // otherwise return Err with a message.\n" -#: src/android.md:1 -msgid "Welcome to Rust in Android" -msgstr "" +#: src/unsafe-rust/exercise.md +msgid "// Keep calling readdir until we get a NULL pointer back.\n" +msgstr "// Keep calling readdir until we get a NULL pointer back.\n" -#: src/android.md:3 +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "// Call closedir as needed.\n" +msgstr "// Call closedir as needed.\n" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +#: src/android/interoperability/with-c/rust.md +msgid "\".\"" +msgstr "\".\"" + +#: src/unsafe-rust/exercise.md src/unsafe-rust/solution.md +msgid "\"files: {:#?}\"" +msgstr "\"files: {:#?}\"" + +#: src/unsafe-rust/solution.md +msgid "\"Invalid path: {err}\"" +msgstr "\"Invalid path: {err}\"" + +#: src/unsafe-rust/solution.md +msgid "// SAFETY: path.as_ptr() cannot be NULL.\n" +msgstr "// SAFETY: path.as_ptr() cannot be NULL.\n" + +#: src/unsafe-rust/solution.md +msgid "\"Could not open {:?}\"" +msgstr "\"Could not open {:?}\"" + +#: src/unsafe-rust/solution.md msgid "" -"Rust is supported for native platform development on Android. This means " -"that you can write new operating system services in Rust, as well as " -"extending existing services." +"// Keep calling readdir until we get a NULL pointer back.\n" +" // SAFETY: self.dir is never NULL.\n" msgstr "" +"// Keep calling readdir until we get a NULL pointer back.\n" +" // SAFETY: self.dir is never NULL.\n" -#: src/android.md:7 +#: src/unsafe-rust/solution.md +msgid "// We have reached the end of the directory.\n" +msgstr "// We have reached the end of the directory.\n" + +#: src/unsafe-rust/solution.md +msgid "" +"// SAFETY: dirent is not NULL and dirent.d_name is NUL\n" +" // terminated.\n" +msgstr "" +"// SAFETY: dirent is not NULL and dirent.d_name is NUL\n" +" // terminated.\n" + +#: src/unsafe-rust/solution.md +msgid "// SAFETY: self.dir is not NULL.\n" +msgstr "// SAFETY: self.dir is not NULL.\n" + +#: src/unsafe-rust/solution.md +msgid "\"Could not close {:?}\"" +msgstr "\"Could not close {:?}\"" + +#: src/unsafe-rust/solution.md +msgid "\"no-such-directory\"" +msgstr "\"no-such-directory\"" + +#: src/unsafe-rust/solution.md +msgid "\"Non UTF-8 character in path\"" +msgstr "\"Non UTF-8 character in path\"" + +#: src/unsafe-rust/solution.md +msgid "\"..\"" +msgstr "\"..\"" + +#: src/unsafe-rust/solution.md +msgid "\"foo.txt\"" +msgstr "\"foo.txt\"" + +#: src/unsafe-rust/solution.md +msgid "\"The Foo Diaries\\n\"" +msgstr "\"The Foo Diaries\\n\"" + +#: src/unsafe-rust/solution.md +msgid "\"bar.png\"" +msgstr "\"bar.png\"" + +#: src/unsafe-rust/solution.md +msgid "\"\\n\"" +msgstr "\"\\n\"" + +#: src/unsafe-rust/solution.md +msgid "\"crab.rs\"" +msgstr "\"crab.rs\"" + +#: src/unsafe-rust/solution.md +msgid "\"//! Crab\\n\"" +msgstr "\"//! Crab\\n\"" + +#: src/android.md +msgid "Welcome to Rust in Android" +msgstr "歡迎在 Android 中使用 Rust" + +#: src/android.md +msgid "" +"Rust is supported for system software on Android. This means that you can " +"write new services, libraries, drivers or even firmware in Rust (or improve " +"existing code as needed)." +msgstr "" +"Android 的系統軟體支援 Rust。也就是說,您可以在 Rust 中編寫新的服務、程式庫、" +"驅動程式,甚至是韌體,也可以視需要強化現有程式碼。" + +#: src/android.md msgid "" "We will attempt to call Rust from one of your own projects today. So try to " "find a little corner of your code base where we can move some lines of code " "to Rust. The fewer dependencies and \"exotic\" types the better. Something " "that parses some raw bytes would be ideal." msgstr "" +"今天我們會嘗試在您擁有的其中一項專案中呼叫 Rust。因此,請盡量在程式碼集中找出" +"一小段來改寫成 Rust。請注意,依附元件和「獨特」型別越少越好。理想情況是確保程" +"式碼能剖析部分原始位元組。" -#: src/android/setup.md:3 +#: src/android.md msgid "" -"We will be using an Android Virtual Device to test our code. Make sure you " -"have access to one or create a new one with:" -msgstr "" +"The speaker may mention any of the following given the increased use of Rust " +"in Android:" +msgstr "由於 Rust 在 Android 中越來越廣為使用,講者可能可以提到以下議題:" -#: src/android/setup.md:6 +#: src/android.md msgid "" -"```shell\n" -"$ source build/envsetup.sh\n" -"$ lunch aosp_cf_x86_64_phone-userdebug\n" -"$ acloud create\n" -"```" +"Service example: [DNS over HTTP](https://security.googleblog.com/2022/07/dns-" +"over-http3-in-android.html)" msgstr "" +"服務範例:[DNS_over_HTTP](https://security.googleblog.com/2022/07/dns-over-" +"http3-in-android.html)" -#: src/android/setup.md:12 +#: src/android.md +msgid "" +"Libraries: [Rutabaga Virtual Graphics Interface](https://crosvm.dev/book/" +"appendix/rutabaga_gfx.html)" +msgstr "" +"程式庫:[Rutabaga 虛擬繪圖介面](https://crosvm.dev/book/appendix/" +"rutabaga_gfx.html)" + +#: src/android.md +msgid "" +"Kernel Drivers: [Binder](https://lore.kernel.org/rust-for-linux/20231101-" +"rust-binder-v1-0-08ba9197f637@google.com/)" +msgstr "" +"核心驅動程式:[Binder](https://lore.kernel.org/rust-for-linux/20231101-rust-" +"binder-v1-0-08ba9197f637@google.com/)" + +#: src/android.md +msgid "" +"Firmware: [pKVM firmware](https://security.googleblog.com/2023/10/bare-metal-" +"rust-in-android.html)" +msgstr "" +"韌體:[pKVM 韌體](https://security.googleblog.com/2023/10/bare-metal-rust-in-" +"android.html)" + +#: src/android/setup.md +msgid "" +"We will be using a Cuttlefish Android Virtual Device to test our code. Make " +"sure you have access to one or create a new one with:" +msgstr "" +"我們會使用 Cuttlefish Android 虛擬裝置來測試程式碼。請確認您可以存取這項裝" +"置,或是使用下方程式碼建立新裝置:" + +#: src/android/setup.md msgid "" "Please see the [Android Developer Codelab](https://source.android.com/docs/" "setup/start) for details." msgstr "" +"詳情請參閱 [Android 開發人員程式碼研究室](https://source.android.com/docs/" +"setup/start)。" -#: src/android/build-rules.md:3 +#: src/android/setup.md +msgid "" +"Cuttlefish is a reference Android device designed to work on generic Linux " +"desktops. MacOS support is also planned." +msgstr "" +"Cuttlefish 是參考用的 Android 裝置,可在一般 Linux 電腦上運作。日後也計劃支" +"援 MacOS。" + +#: src/android/setup.md +msgid "" +"The Cuttlefish system image maintains high fidelity to real devices, and is " +"the ideal emulator to run many Rust use cases." +msgstr "" +"Cuttlefish 系統映像檔能維持媲美實體裝置的高保真度,是可用於許多 Rust 用途的理" +"想模擬器。" + +#: src/android/build-rules.md msgid "The Android build system (Soong) supports Rust via a number of modules:" msgstr "Android 的建構系統 (Soong) 透過以下模組支援 Rust:" -#: src/android/build-rules.md:5 +#: src/android/build-rules.md msgid "Module Type" msgstr "模組型態" -#: src/android/build-rules.md:5 +#: src/android/build-rules.md msgid "Description" msgstr "敘述" -#: src/android/build-rules.md:7 +#: src/android/build-rules.md msgid "`rust_binary`" msgstr "`rust_binary`" -#: src/android/build-rules.md:7 +#: src/android/build-rules.md msgid "Produces a Rust binary." msgstr "生成一個 Rust 執行檔。" -#: src/android/build-rules.md:8 +#: src/android/build-rules.md msgid "`rust_library`" msgstr "`rust_library`" -#: src/android/build-rules.md:8 +#: src/android/build-rules.md msgid "Produces a Rust library, and provides both `rlib` and `dylib` variants." msgstr "生成一個 Rust 函式庫,及其對應的 `rlib` 和 `dylib` 變體。" -#: src/android/build-rules.md:9 +#: src/android/build-rules.md msgid "`rust_ffi`" msgstr "`rust_ffi`" -#: src/android/build-rules.md:9 +#: src/android/build-rules.md msgid "" "Produces a Rust C library usable by `cc` modules, and provides both static " "and shared variants." msgstr "生成一個可被 `cc` 模組使用的 Rust C 函式庫,及其對應的靜態和共享變體。" -#: src/android/build-rules.md:10 +#: src/android/build-rules.md msgid "`rust_proc_macro`" msgstr "`rust_proc_macro`" -#: src/android/build-rules.md:10 +#: src/android/build-rules.md msgid "" "Produces a `proc-macro` Rust library. These are analogous to compiler " "plugins." msgstr "生成一個 `proc-macro` Rust 函式庫,類似於編譯器 擴充。" -#: src/android/build-rules.md:11 +#: src/android/build-rules.md msgid "`rust_test`" msgstr "`rust_test`" -#: src/android/build-rules.md:11 +#: src/android/build-rules.md msgid "Produces a Rust test binary that uses the standard Rust test harness." msgstr "使用Rust自動化測試框架,生成一個 Rust 測試檔。" -#: src/android/build-rules.md:12 +#: src/android/build-rules.md msgid "`rust_fuzz`" msgstr "`rust_fuzz`" -#: src/android/build-rules.md:12 +#: src/android/build-rules.md msgid "Produces a Rust fuzz binary leveraging `libfuzzer`." msgstr "生成一個使用 `libfuzzer` 的 Rust 模糊測試執行檔。" -#: src/android/build-rules.md:13 +#: src/android/build-rules.md msgid "`rust_protobuf`" msgstr "`rust_protobuf`" -#: src/android/build-rules.md:13 +#: src/android/build-rules.md msgid "" "Generates source and produces a Rust library that provides an interface for " "a particular protobuf." msgstr "生成對應 protobuf 介面的 Rust 原始碼及函式庫。" -#: src/android/build-rules.md:14 +#: src/android/build-rules.md msgid "`rust_bindgen`" msgstr "`rust_bindgen`" -#: src/android/build-rules.md:14 +#: src/android/build-rules.md msgid "" "Generates source and produces a Rust library containing Rust bindings to C " "libraries." msgstr "生成用於連接 C 函式庫的 Rust 原始碼及函式庫。" -#: src/android/build-rules.md:16 +#: src/android/build-rules.md msgid "We will look at `rust_binary` and `rust_library` next." msgstr "接下來我們會探討 `rust_binary` 及 `rust_library`。" -#: src/android/build-rules/binary.md:1 -msgid "Rust Binaries" -msgstr "" +#: src/android/build-rules.md +msgid "Additional items speaker may mention:" +msgstr "講者可以提及以下其他事項:" -#: src/android/build-rules/binary.md:3 +#: src/android/build-rules.md +msgid "" +"Cargo is not optimized for multi-language repos, and also downloads packages " +"from the internet." +msgstr "" +"Cargo 未針對使用多種程式語言的倉儲進行最佳化調整,並且會從網際網路下載套件。" + +#: src/android/build-rules.md +msgid "" +"For compliance and performance, Android must have crates in-tree. It must " +"also interop with C/C++/Java code. Soong fills that gap." +msgstr "" +"為了遵循常規並確保效能,Android 必須在自身專案內提供 Crate。此外,也必須保有" +"與 C/C++/Java 程式碼的互通性。Soong 可以彌補這中間的落差。" + +#: src/android/build-rules.md +msgid "" +"Soong has many similarities to Bazel, which is the open-source variant of " +"Blaze (used in google3)." +msgstr "" +"Soong 與 Bazel 有許多相似之處,後者是 Blaze 的開放原始碼變化版本 (用於 " +"google3)。" + +#: src/android/build-rules.md +msgid "" +"There is a plan to transition [Android](https://source.android.com/docs/" +"setup/build/bazel/introduction), [ChromeOS](https://chromium.googlesource." +"com/chromiumos/bazel/), and [Fuchsia](https://source.android.com/docs/setup/" +"build/bazel/introduction) to Bazel." +msgstr "" +"Google 有將 [Android](https://source.android.com/docs/setup/build/bazel/" +"introduction)、[ChromeOS](https://chromium.googlesource.com/chromiumos/" +"bazel/) 和 [Fuchsia](https://source.android.com/docs/setup/build/bazel/" +"introduction) 轉移到 Bazel 的規畫。" + +#: src/android/build-rules.md +msgid "Learning Bazel-like build rules is useful for all Rust OS developers." +msgstr "對所有 Rust OS 開發人員來說,學習類似 Bazel 的建構規則都能派上用場。" + +#: src/android/build-rules.md +msgid "Fun fact: Data from Star Trek is a Soong-type Android." +msgstr "" +"趣味小知識:《星艦迷航記》中的「百科 (Data)」是 Soong 型的仿生機器人 " +"(android)。" + +#: src/android/build-rules/binary.md +msgid "Rust Binaries" +msgstr "Rust 二進位檔" + +#: src/android/build-rules/binary.md msgid "" "Let us start with a simple application. At the root of an AOSP checkout, " "create the following files:" msgstr "" +"我們從一個簡單的應用程式開始著手。請在 Android 開放原始碼計畫程式庫的根層級," +"建立下列檔案:" -#: src/android/build-rules/binary.md:6 src/android/build-rules/library.md:13 +#: src/android/build-rules/binary.md src/android/build-rules/library.md msgid "_hello_rust/Android.bp_:" -msgstr "" +msgstr "_hello_rust/Android.bp_:" -#: src/android/build-rules/binary.md:8 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"hello_rust\",\n" -" crate_name: \"hello_rust\",\n" -" srcs: [\"src/main.rs\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/build-rules/binary.md +msgid "\"hello_rust\"" +msgstr "\"hello_rust\"" -#: src/android/build-rules/binary.md:16 src/android/build-rules/library.md:34 +#: src/android/build-rules/binary.md src/android/build-rules/library.md +#: src/android/logging.md +msgid "\"src/main.rs\"" +msgstr "\"src/main.rs\"" + +#: src/android/build-rules/binary.md src/android/build-rules/library.md msgid "_hello_rust/src/main.rs_:" -msgstr "" +msgstr "_hello_rust/src/main.rs_:" -#: src/android/build-rules/binary.md:18 -msgid "" -"```rust\n" -"//! Rust demo.\n" -"\n" -"/// Prints a greeting to standard output.\n" -"fn main() {\n" -" println!(\"Hello from Rust!\");\n" -"}\n" -"```" -msgstr "" +#: src/android/build-rules/binary.md src/android/build-rules/library.md +msgid "//! Rust demo.\n" +msgstr "//! Rust demo.\n" -#: src/android/build-rules/binary.md:27 +#: src/android/build-rules/binary.md src/android/build-rules/library.md +msgid "/// Prints a greeting to standard output.\n" +msgstr "/// Prints a greeting to standard output.\n" + +#: src/android/build-rules/binary.md src/exercises/chromium/build-rules.md +msgid "\"Hello from Rust!\"" +msgstr "\"Hello from Rust!\"" + +#: src/android/build-rules/binary.md msgid "You can now build, push, and run the binary:" -msgstr "" +msgstr "您現在可以建構、推送及執行二進位檔:" -#: src/android/build-rules/binary.md:29 +#: src/android/build-rules/binary.md msgid "" "```shell\n" -"$ m hello_rust\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust /data/local/tmp\"\n" -"$ adb shell /data/local/tmp/hello_rust\n" -"Hello from Rust!\n" +"m hello_rust\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust\" /data/local/tmp\n" +"adb shell /data/local/tmp/hello_rust\n" "```" msgstr "" +"```shell\n" +"m hello_rust\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust\" /data/local/tmp\n" +"adb shell /data/local/tmp/hello_rust\n" +"```" -#: src/android/build-rules/library.md:1 +#: src/android/build-rules/library.md msgid "Rust Libraries" -msgstr "" +msgstr "Rust 程式庫" -#: src/android/build-rules/library.md:3 +#: src/android/build-rules/library.md msgid "You use `rust_library` to create a new Rust library for Android." -msgstr "" +msgstr "您可以使用 `rust_library` 為 Android 建立一個新的 Rust 程式庫。" -#: src/android/build-rules/library.md:5 +#: src/android/build-rules/library.md msgid "Here we declare a dependency on two libraries:" -msgstr "" +msgstr "這裡,我們會宣告兩個需要依附的程式庫:" -#: src/android/build-rules/library.md:7 +#: src/android/build-rules/library.md msgid "`libgreeting`, which we define below," -msgstr "" +msgstr "`libgreeting` (定義如下)" -#: src/android/build-rules/library.md:8 +#: src/android/build-rules/library.md msgid "" "`libtextwrap`, which is a crate already vendored in [`external/rust/crates/`]" "(https://cs.android.com/android/platform/superproject/+/master:external/rust/" "crates/)." msgstr "" +"`libtextwrap` (隨附於 [`external/rust/crates/`](https://cs.android.com/" +"android/platform/superproject/+/master:external/rust/crates/) 的 Crate 中)" -#: src/android/build-rules/library.md:15 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"hello_rust_with_dep\",\n" -" crate_name: \"hello_rust_with_dep\",\n" -" srcs: [\"src/main.rs\"],\n" -" rustlibs: [\n" -" \"libgreetings\",\n" -" \"libtextwrap\",\n" -" ],\n" -" prefer_rlib: true,\n" -"}\n" -"\n" -"rust_library {\n" -" name: \"libgreetings\",\n" -" crate_name: \"greetings\",\n" -" srcs: [\"src/lib.rs\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/build-rules/library.md +msgid "\"hello_rust_with_dep\"" +msgstr "\"hello_rust_with_dep\"" -#: src/android/build-rules/library.md:36 -msgid "" -"```rust,ignore\n" -"//! Rust demo.\n" -"\n" -"use greetings::greeting;\n" -"use textwrap::fill;\n" -"\n" -"/// Prints a greeting to standard output.\n" -"fn main() {\n" -" println!(\"{}\", fill(&greeting(\"Bob\"), 24));\n" -"}\n" -"```" -msgstr "" +#: src/android/build-rules/library.md +msgid "\"libgreetings\"" +msgstr "\"libgreetings\"" -#: src/android/build-rules/library.md:48 +#: src/android/build-rules/library.md +msgid "\"libtextwrap\"" +msgstr "\"libtextwrap\"" + +#: src/android/build-rules/library.md +msgid "// Need this to avoid dynamic link error.\n" +msgstr "// Need this to avoid dynamic link error.\n" + +#: src/android/build-rules/library.md +msgid "\"greetings\"" +msgstr "\"greetings\"" + +#: src/android/build-rules/library.md +#: src/android/aidl/example-service/service.md src/android/testing.md +#: src/android/interoperability/java.md +msgid "\"src/lib.rs\"" +msgstr "\"src/lib.rs\"" + +#: src/android/build-rules/library.md msgid "_hello_rust/src/lib.rs_:" -msgstr "" +msgstr "_hello_rust/src/lib.rs_:" -#: src/android/build-rules/library.md:50 -msgid "" -"```rust,ignore\n" -"//! Greeting library.\n" -"\n" -"/// Greet `name`.\n" -"pub fn greeting(name: &str) -> String {\n" -" format!(\"Hello {name}, it is very nice to meet you!\")\n" -"}\n" -"```" -msgstr "" +#: src/android/build-rules/library.md +msgid "//! Greeting library.\n" +msgstr "//! Greeting library.\n" -#: src/android/build-rules/library.md:59 +#: src/android/build-rules/library.md +msgid "/// Greet `name`.\n" +msgstr "/// Greet `name`.\n" + +#: src/android/build-rules/library.md +msgid "\"Hello {name}, it is very nice to meet you!\"" +msgstr "\"Hello {name}, it is very nice to meet you!\"" + +#: src/android/build-rules/library.md msgid "You build, push, and run the binary like before:" -msgstr "" +msgstr "請按照之前的方式,建構、推送及執行二進位檔:" -#: src/android/build-rules/library.md:61 +#: src/android/build-rules/library.md msgid "" "```shell\n" -"$ m hello_rust_with_dep\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/hello_rust_with_dep\n" -"Hello Bob, it is very\n" -"nice to meet you!\n" +"m hello_rust_with_dep\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/hello_rust_with_dep\n" "```" msgstr "" +"```shell\n" +"m hello_rust_with_dep\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/hello_rust_with_dep\n" +"```" -#: src/android/aidl.md:3 +#: src/android/aidl.md msgid "" "The [Android Interface Definition Language (AIDL)](https://developer.android." "com/guide/components/aidl) is supported in Rust:" msgstr "" +"Rust 支援 [Android 介面定義語言 (AIDL)](https://developer.android.com/guide/" +"components/aidl):" -#: src/android/aidl.md:6 +#: src/android/aidl.md msgid "Rust code can call existing AIDL servers," -msgstr "" +msgstr "Rust 程式碼可以呼叫現有的 AIDL 服務。" -#: src/android/aidl.md:7 +#: src/android/aidl.md msgid "You can create new AIDL servers in Rust." +msgstr "您可以在 Rust 中建立新的 AIDL 服務。" + +#: src/android/aidl/birthday-service.md +msgid "" +"To illustrate how to use Rust with Binder, we're going to walk through the " +"process of creating a Binder interface. We're then going to both implement " +"the described service and write client code that talks to that service." msgstr "" -#: src/android/aidl/interface.md:1 +#: src/android/aidl/example-service/interface.md msgid "AIDL Interfaces" -msgstr "" +msgstr "AIDL 介面" -#: src/android/aidl/interface.md:3 +#: src/android/aidl/example-service/interface.md msgid "You declare the API of your service using an AIDL interface:" -msgstr "" +msgstr "您可以使用 AIDL 介面宣告服務的 API:" -#: src/android/aidl/interface.md:5 +#: src/android/aidl/example-service/interface.md +#: src/android/aidl/example-service/service-bindings.md msgid "" "_birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl_:" msgstr "" +"_birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl_:" -#: src/android/aidl/interface.md:7 -msgid "" -"```java\n" -"package com.example.birthdayservice;\n" -"\n" -"/** Birthday service interface. */\n" -"interface IBirthdayService {\n" -" /** Generate a Happy Birthday message. */\n" -" String wishHappyBirthday(String name, int years);\n" -"}\n" -"```" -msgstr "" +#: src/android/aidl/example-service/interface.md +#: src/android/aidl/example-service/service-bindings.md +#: src/android/aidl/example-service/changing-definition.md +msgid "/** Birthday service interface. */" +msgstr "/** Birthday service interface. */" -#: src/android/aidl/interface.md:17 +#: src/android/aidl/example-service/interface.md +#: src/android/aidl/example-service/service-bindings.md +#: src/android/aidl/example-service/changing-definition.md +msgid "/** Generate a Happy Birthday message. */" +msgstr "/** Generate a Happy Birthday message. */" + +#: src/android/aidl/example-service/interface.md msgid "_birthday_service/aidl/Android.bp_:" -msgstr "" +msgstr "_birthday_service/aidl/Android.bp_:" -#: src/android/aidl/interface.md:19 +#: src/android/aidl/example-service/interface.md +msgid "\"com.example.birthdayservice\"" +msgstr "\"com.example.birthdayservice\"" + +#: src/android/aidl/example-service/interface.md +msgid "\"com/example/birthdayservice/*.aidl\"" +msgstr "\"com/example/birthdayservice/*.aidl\"" + +#: src/android/aidl/example-service/interface.md +msgid "// Rust is not enabled by default\n" +msgstr "// Rust is not enabled by default\n" + +#: src/android/aidl/example-service/interface.md msgid "" -"```javascript\n" -"aidl_interface {\n" -" name: \"com.example.birthdayservice\",\n" -" srcs: [\"com/example/birthdayservice/*.aidl\"],\n" -" unstable: true,\n" -" backend: {\n" -" rust: { // Rust is not enabled by default\n" -" enabled: true,\n" -" },\n" -" },\n" -"}\n" -"```" +"Note that the directory structure under the `aidl/` directory needs to match " +"the package name used in the AIDL file, i.e. the package is `com.example." +"birthdayservice` and the file is at `aidl/com/example/IBirthdayService.aidl`." msgstr "" -#: src/android/aidl/interface.md:32 +#: src/android/aidl/example-service/service-bindings.md +msgid "Generated Service API" +msgstr "" + +#: src/android/aidl/example-service/service-bindings.md msgid "" -"Add `vendor_available: true` if your AIDL file is used by a binary in the " -"vendor partition." +"Binder generates a trait corresponding to the interface definition. trait to " +"talk to the service." msgstr "" -#: src/android/aidl/implementation.md:1 +#: src/android/aidl/example-service/service-bindings.md +#, fuzzy +msgid "_Generated trait_:" +msgstr "生成的特徵:" + +#: src/android/aidl/example-service/service-bindings.md +msgid "" +"Your service will need to implement this trait, and your client will use " +"this trait to talk to the service." +msgstr "" + +#: src/android/aidl/example-service/service-bindings.md +msgid "" +"The generated bindings can be found at `out/soong/.intermediates//`." +msgstr "" + +#: src/android/aidl/example-service/service-bindings.md +msgid "" +"Point out how the generated function signature, specifically the argument " +"and return types, correspond the interface definition." +msgstr "" + +#: src/android/aidl/example-service/service-bindings.md +msgid "" +"`String` for an argument results in a different Rust type than `String` as a " +"return type." +msgstr "" + +#: src/android/aidl/example-service/service.md msgid "Service Implementation" -msgstr "" +msgstr "服務實作" -#: src/android/aidl/implementation.md:3 +#: src/android/aidl/example-service/service.md msgid "We can now implement the AIDL service:" -msgstr "" +msgstr "我們現在可以實作 AIDL 服務了:" -#: src/android/aidl/implementation.md:5 +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/changing-implementation.md msgid "_birthday_service/src/lib.rs_:" -msgstr "" +msgstr "_birthday_service/src/lib.rs_:" -#: src/android/aidl/implementation.md:7 -msgid "" -"```rust,ignore\n" -"//! Implementation of the `IBirthdayService` AIDL interface.\n" -"use com_example_birthdayservice::aidl::com::example::birthdayservice::" -"IBirthdayService::IBirthdayService;\n" -"use com_example_birthdayservice::binder;\n" -"\n" -"/// The `IBirthdayService` implementation.\n" -"pub struct BirthdayService;\n" -"\n" -"impl binder::Interface for BirthdayService {}\n" -"\n" -"impl IBirthdayService for BirthdayService {\n" -" fn wishHappyBirthday(&self, name: &str, years: i32) -> binder::" -"Result {\n" -" Ok(format!(\n" -" \"Happy Birthday {name}, congratulations with the {years} years!" -"\"\n" -" ))\n" -" }\n" -"}\n" -"```" -msgstr "" +#: src/android/aidl/example-service/service.md +msgid "/// The `IBirthdayService` implementation.\n" +msgstr "/// The `IBirthdayService` implementation.\n" -#: src/android/aidl/implementation.md:26 src/android/aidl/server.md:28 -#: src/android/aidl/client.md:37 +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/changing-implementation.md +#: src/android/aidl/types/file-descriptor.md +msgid "\"Happy Birthday {name}, congratulations with the {years} years!\"" +msgstr "\"Happy Birthday {name}, congratulations with the {years} years!\"" + +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/server.md +#: src/android/aidl/example-service/client.md msgid "_birthday_service/Android.bp_:" -msgstr "" +msgstr "_birthday_service/Android.bp_:" -#: src/android/aidl/implementation.md:28 +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/server.md +msgid "\"libbirthdayservice\"" +msgstr "\"libbirthdayservice\"" + +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/server.md +#: src/android/aidl/example-service/client.md +msgid "\"birthdayservice\"" +msgstr "\"birthdayservice\"" + +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/server.md +#: src/android/aidl/example-service/client.md +msgid "\"com.example.birthdayservice-rust\"" +msgstr "\"com.example.birthdayservice-rust\"" + +#: src/android/aidl/example-service/service.md +#: src/android/aidl/example-service/server.md +#: src/android/aidl/example-service/client.md +msgid "\"libbinder_rs\"" +msgstr "\"libbinder_rs\"" + +#: src/android/aidl/example-service/service.md msgid "" -"```javascript\n" -"rust_library {\n" -" name: \"libbirthdayservice\",\n" -" srcs: [\"src/lib.rs\"],\n" -" crate_name: \"birthdayservice\",\n" -" rustlibs: [\n" -" \"com.example.birthdayservice-rust\",\n" -" \"libbinder_rs\",\n" -" ],\n" -"}\n" -"```" +"Point out the path to the generated `IBirthdayService` trait, and explain " +"why each of the segments is necessary." msgstr "" -#: src/android/aidl/server.md:1 +#: src/android/aidl/example-service/service.md +msgid "" +"TODO: What does the `binder::Interface` trait do? Are there methods to " +"override? Where source?" +msgstr "" + +#: src/android/aidl/example-service/server.md msgid "AIDL Server" -msgstr "" +msgstr "AIDL 伺服器" -#: src/android/aidl/server.md:3 +#: src/android/aidl/example-service/server.md msgid "Finally, we can create a server which exposes the service:" -msgstr "" +msgstr "最後,我們可以建立伺服器來公開服務:" -#: src/android/aidl/server.md:5 +#: src/android/aidl/example-service/server.md msgid "_birthday_service/src/server.rs_:" -msgstr "" +msgstr "_birthday_service/src/server.rs_:" -#: src/android/aidl/server.md:7 +#: src/android/aidl/example-service/server.md +msgid "//! Birthday service.\n" +msgstr "//! Birthday service.\n" + +#: src/android/aidl/example-service/server.md +msgid "/// Entry point for birthday service.\n" +msgstr "/// Entry point for birthday service.\n" + +#: src/android/aidl/example-service/server.md +msgid "\"Failed to register service\"" +msgstr "\"Failed to register service\"" + +#: src/android/aidl/example-service/server.md +msgid "\"birthday_server\"" +msgstr "\"birthday_server\"" + +#: src/android/aidl/example-service/server.md +msgid "\"src/server.rs\"" +msgstr "\"src/server.rs\"" + +#: src/android/aidl/example-service/server.md +#: src/android/aidl/example-service/client.md +msgid "// To avoid dynamic link error.\n" +msgstr "// To avoid dynamic link error.\n" + +#: src/android/aidl/example-service/server.md msgid "" -"```rust,ignore\n" -"//! Birthday service.\n" -"use birthdayservice::BirthdayService;\n" -"use com_example_birthdayservice::aidl::com::example::birthdayservice::" -"IBirthdayService::BnBirthdayService;\n" -"use com_example_birthdayservice::binder;\n" -"\n" -"const SERVICE_IDENTIFIER: &str = \"birthdayservice\";\n" -"\n" -"/// Entry point for birthday service.\n" -"fn main() {\n" -" let birthday_service = BirthdayService;\n" -" let birthday_service_binder = BnBirthdayService::new_binder(\n" -" birthday_service,\n" -" binder::BinderFeatures::default(),\n" -" );\n" -" binder::add_service(SERVICE_IDENTIFIER, birthday_service_binder." -"as_binder())\n" -" .expect(\"Failed to register service\");\n" -" binder::ProcessState::join_thread_pool()\n" -"}\n" -"```" +"The process for taking a user-defined service implementation (in this case " +"the `BirthdayService` type, which implements the `IBirthdayService`) and " +"starting it as a Binder service has multiple steps, and may appear more " +"complicated than students are used to if they've used Binder from C++ or " +"another language. Explain to students why each step is necessary." msgstr "" -#: src/android/aidl/server.md:30 +#: src/android/aidl/example-service/server.md +msgid "Create an instance of your service type (`BirthdayService`)." +msgstr "" + +#: src/android/aidl/example-service/server.md msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"birthday_server\",\n" -" crate_name: \"birthday_server\",\n" -" srcs: [\"src/server.rs\"],\n" -" rustlibs: [\n" -" \"com.example.birthdayservice-rust\",\n" -" \"libbinder_rs\",\n" -" \"libbirthdayservice\",\n" -" ],\n" -" prefer_rlib: true,\n" -"}\n" -"```" +"Wrap the service object in corresponding `Bn*` type (`BnBirthdayService` in " +"this case). This type is generated by Binder and provides the common Binder " +"functionality that would be provided by the `BnBinder` base class in C++. We " +"don't have inheritance in Rust, so instead we use composition, putting our " +"`BirthdayService` within the generated `BnBinderService`." msgstr "" -#: src/android/aidl/deploy.md:3 +#: src/android/aidl/example-service/server.md +msgid "" +"Call `add_service`, giving it a service identifier and your service object " +"(the `BnBirthdayService` object in the example)." +msgstr "" + +#: src/android/aidl/example-service/server.md +msgid "" +"Call `join_thread_pool` to add the current thread to Binder's thread pool " +"and start listening for connections." +msgstr "" + +#: src/android/aidl/example-service/deploy.md msgid "We can now build, push, and start the service:" -msgstr "" +msgstr "現在我們可以建構、推送及啟動服務:" -#: src/android/aidl/deploy.md:5 +#: src/android/aidl/example-service/deploy.md msgid "" "```shell\n" -"$ m birthday_server\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_server /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/birthday_server\n" +"m birthday_server\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_server\" /data/local/" +"tmp\n" +"adb root\n" +"adb shell /data/local/tmp/birthday_server\n" "```" msgstr "" +"```shell\n" +"m birthday_server\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_server\" /data/local/" +"tmp\n" +"adb root\n" +"adb shell /data/local/tmp/birthday_server\n" +"```" -#: src/android/aidl/deploy.md:11 +#: src/android/aidl/example-service/deploy.md msgid "In another terminal, check that the service runs:" -msgstr "" +msgstr "在另一個終端機中,檢查服務是否能執行:" -#: src/android/aidl/deploy.md:13 -msgid "" -"```shell\n" -"$ adb shell service check birthdayservice\n" -"Service birthdayservice: found\n" -"```" -msgstr "" - -#: src/android/aidl/deploy.md:18 +#: src/android/aidl/example-service/deploy.md msgid "You can also call the service with `service call`:" -msgstr "" +msgstr "藉由 `service call` 呼叫,您也可以呼叫服務:" -#: src/android/aidl/deploy.md:20 -msgid "" -"```shell\n" -"$ $ adb shell service call birthdayservice 1 s16 Bob i32 24\n" -"Result: Parcel(\n" -" 0x00000000: 00000000 00000036 00610048 00700070 '....6...H.a.p.p.'\n" -" 0x00000010: 00200079 00690042 00740072 00640068 'y. .B.i.r.t.h.d.'\n" -" 0x00000020: 00790061 00420020 0062006f 0020002c 'a.y. .B.o.b.,. .'\n" -" 0x00000030: 006f0063 0067006e 00610072 00750074 'c.o.n.g.r.a.t.u.'\n" -" 0x00000040: 0061006c 00690074 006e006f 00200073 'l.a.t.i.o.n.s. .'\n" -" 0x00000050: 00690077 00680074 00740020 00650068 'w.i.t.h. .t.h.e.'\n" -" 0x00000060: 00320020 00200034 00650079 00720061 ' .2.4. .y.e.a.r.'\n" -" 0x00000070: 00210073 00000000 's.!..... ')\n" -"```" -msgstr "" - -#: src/android/aidl/client.md:1 +#: src/android/aidl/example-service/client.md msgid "AIDL Client" -msgstr "" +msgstr "AIDL 用戶端" -#: src/android/aidl/client.md:3 +#: src/android/aidl/example-service/client.md msgid "Finally, we can create a Rust client for our new service." -msgstr "" +msgstr "最後,我們可以為新服務建立 Rust 用戶端。" -#: src/android/aidl/client.md:5 +#: src/android/aidl/example-service/client.md +#: src/android/aidl/example-service/changing-implementation.md msgid "_birthday_service/src/client.rs_:" -msgstr "" +msgstr "_birthday_service/src/client.rs_:" -#: src/android/aidl/client.md:7 -msgid "" -"```rust,ignore\n" -"//! Birthday service.\n" -"use com_example_birthdayservice::aidl::com::example::birthdayservice::" -"IBirthdayService::IBirthdayService;\n" -"use com_example_birthdayservice::binder;\n" -"\n" -"const SERVICE_IDENTIFIER: &str = \"birthdayservice\";\n" -"\n" -"/// Connect to the BirthdayService.\n" -"pub fn connect() -> Result, binder::" -"StatusCode> {\n" -" binder::get_interface(SERVICE_IDENTIFIER)\n" -"}\n" -"\n" -"/// Call the birthday service.\n" -"fn main() -> Result<(), binder::Status> {\n" -" let name = std::env::args()\n" -" .nth(1)\n" -" .unwrap_or_else(|| String::from(\"Bob\"));\n" -" let years = std::env::args()\n" -" .nth(2)\n" -" .and_then(|arg| arg.parse::().ok())\n" -" .unwrap_or(42);\n" -"\n" -" binder::ProcessState::start_thread_pool();\n" -" let service = connect().expect(\"Failed to connect to " -"BirthdayService\");\n" -" let msg = service.wishHappyBirthday(&name, years)?;\n" -" println!(\"{msg}\");\n" -" Ok(())\n" -"}\n" -"```" -msgstr "" +#: src/android/aidl/example-service/client.md +msgid "/// Call the birthday service.\n" +msgstr "/// Call the birthday service.\n" -#: src/android/aidl/client.md:39 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"birthday_client\",\n" -" crate_name: \"birthday_client\",\n" -" srcs: [\"src/client.rs\"],\n" -" rustlibs: [\n" -" \"com.example.birthdayservice-rust\",\n" -" \"libbinder_rs\",\n" -" ],\n" -" prefer_rlib: true,\n" -"}\n" -"```" -msgstr "" +#: src/android/aidl/example-service/client.md src/android/aidl/types/objects.md +#: src/android/aidl/types/parcelables.md +#: src/android/aidl/types/file-descriptor.md +msgid "\"Failed to connect to BirthdayService\"" +msgstr "\"Failed to connect to BirthdayService\"" -#: src/android/aidl/client.md:52 +#: src/android/aidl/example-service/client.md +#, fuzzy +msgid "// Call the service.\n" +msgstr "/// Call the birthday service.\n" + +#: src/android/aidl/example-service/client.md +msgid "\"{msg}\"" +msgstr "\"{msg}\"" + +#: src/android/aidl/example-service/client.md +msgid "\"birthday_client\"" +msgstr "\"birthday_client\"" + +#: src/android/aidl/example-service/client.md +msgid "\"src/client.rs\"" +msgstr "\"src/client.rs\"" + +#: src/android/aidl/example-service/client.md msgid "Notice that the client does not depend on `libbirthdayservice`." -msgstr "" +msgstr "請注意,用戶端並不依賴 `libbirthdayservice`。" -#: src/android/aidl/client.md:54 +#: src/android/aidl/example-service/client.md msgid "Build, push, and run the client on your device:" -msgstr "" +msgstr "建構、推送及在裝置裡執行用戶端程式:" -#: src/android/aidl/client.md:56 +#: src/android/aidl/example-service/client.md msgid "" "```shell\n" -"$ m birthday_client\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_client /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/birthday_client Charlie 60\n" -"Happy Birthday Charlie, congratulations with the 60 years!\n" +"m birthday_client\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_client\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/birthday_client Charlie 60\n" "```" msgstr "" +"```shell\n" +"m birthday_client\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/birthday_client\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/birthday_client Charlie 60\n" +"```" -#: src/android/aidl/changing.md:3 +#: src/android/aidl/example-service/client.md +msgid "" +"`Strong` is the trait object representing the service " +"that the client has connected to." +msgstr "" + +#: src/android/aidl/example-service/client.md +msgid "" +"`Strong` is a custom smart pointer type for Binder. It handles both an in-" +"process ref count for the service trait object, and the global Binder ref " +"count that tracks how many processes have a reference to the object." +msgstr "" + +#: src/android/aidl/example-service/client.md +msgid "" +"Note that the trait object that the client uses to talk to the service uses " +"the exact same trait that the server implements. For a given Binder " +"interface, there is a single Rust trait generated that both client and " +"server use." +msgstr "" + +#: src/android/aidl/example-service/client.md +msgid "" +"Use the same service identifier used when registering the service. This " +"should ideally be defined in a common crate that both the client and server " +"can depend on." +msgstr "" + +#: src/android/aidl/example-service/changing-definition.md msgid "" "Let us extend the API with more functionality: we want to let clients " "specify a list of lines for the birthday card:" msgstr "讓我們為這個 API 擴充更多功能:我們想要讓用戶能在生日卡上指定幾行字:" -#: src/android/aidl/changing.md:6 +#: src/android/aidl/example-service/changing-definition.md +msgid "This results in an updated trait definition for `IBirthdayService`:" +msgstr "" + +#: src/android/aidl/example-service/changing-definition.md msgid "" -"```java\n" -"package com.example.birthdayservice;\n" -"\n" -"/** Birthday service interface. */\n" -"interface IBirthdayService {\n" -" /** Generate a Happy Birthday message. */\n" -" String wishHappyBirthday(String name, int years, in String[] text);\n" -"}\n" +"Note how the `String[]` in the AIDL definition is translated as a " +"`&[String]` in Rust, i.e. that idiomatic Rust types are used in the " +"generated bindings wherever possible:" +msgstr "" + +#: src/android/aidl/example-service/changing-definition.md +msgid "`in` array arguments are translated to slices." +msgstr "" + +#: src/android/aidl/example-service/changing-definition.md +msgid "`out` and `inout` args are translated to `&mut Vec`." +msgstr "" + +#: src/android/aidl/example-service/changing-definition.md +msgid "Return values are translated to returning a `Vec`." +msgstr "" + +#: src/android/aidl/example-service/changing-implementation.md +msgid "Updating Client and Service" +msgstr "" + +#: src/android/aidl/example-service/changing-implementation.md +msgid "Update the client and server code to account for the new API." +msgstr "" + +#: src/android/aidl/example-service/changing-implementation.md +msgid "'\\n'" +msgstr "" + +#: src/android/aidl/example-service/changing-implementation.md +msgid "\"Habby birfday to yuuuuu\"" +msgstr "" + +#: src/android/aidl/example-service/changing-implementation.md +msgid "\"And also: many more\"" +msgstr "" + +#: src/android/aidl/example-service/changing-implementation.md +msgid "" +"TODO: Move code snippets into project files where they'll actually be built?" +msgstr "" + +#: src/android/aidl/types.md +msgid "Working With AIDL Types" +msgstr "" + +#: src/android/aidl/types.md +msgid "AIDL types translate into the appropriate idiomatic Rust type:" +msgstr "" + +#: src/android/aidl/types.md +msgid "Primitive types map (mostly) to idiomatic Rust types." +msgstr "" + +#: src/android/aidl/types.md +msgid "Collection types like slices, `Vec`s and string types are supported." +msgstr "" + +#: src/android/aidl/types.md +msgid "" +"References to AIDL objects and file handles can be sent between clients and " +"services." +msgstr "" + +#: src/android/aidl/types.md +msgid "File handles and parcelables are fully supported." +msgstr "" + +#: src/android/aidl/types/primitives.md +msgid "Primitive types map (mostly) idiomatically:" +msgstr "" + +#: src/android/aidl/types/primitives.md +msgid "AIDL Type" +msgstr "AIDL 型別" + +#: src/android/aidl/types/primitives.md src/android/aidl/types/arrays.md +#: src/android/interoperability/cpp/type-mapping.md +msgid "Rust Type" +msgstr "Rust 型別" + +#: src/android/aidl/types/primitives.md +msgid "Note" +msgstr "" + +#: src/android/aidl/types/primitives.md +msgid "`boolean`" +msgstr "`boolean`" + +#: src/android/aidl/types/primitives.md +msgid "`byte`" +msgstr "`byte`" + +#: src/android/aidl/types/primitives.md +msgid "`i8`" +msgstr "`i8`" + +#: src/android/aidl/types/primitives.md +msgid "Note that bytes are signed." +msgstr "" + +#: src/android/aidl/types/primitives.md +msgid "`u16`" +msgstr "`u16`" + +#: src/android/aidl/types/primitives.md +msgid "Note the usage of `u16`, NOT `u32`." +msgstr "" + +#: src/android/aidl/types/primitives.md +msgid "`int`" +msgstr "`int`" + +#: src/android/aidl/types/primitives.md +msgid "`i32`" +msgstr "`i32`" + +#: src/android/aidl/types/primitives.md +msgid "`long`" +msgstr "`long`" + +#: src/android/aidl/types/primitives.md +msgid "`i64`" +msgstr "`i64`" + +#: src/android/aidl/types/primitives.md +msgid "`float`" +msgstr "`float`" + +#: src/android/aidl/types/primitives.md +msgid "`f32`" +msgstr "`f32`" + +#: src/android/aidl/types/primitives.md +msgid "`double`" +msgstr "`double`" + +#: src/android/aidl/types/primitives.md +msgid "`f64`" +msgstr "`f64`" + +#: src/android/aidl/types/arrays.md +msgid "" +"The array types (`T[]`, `byte[]`, and `List`) get translated to the " +"appropriate Rust array type depending on how they are used in the function " +"signature:" +msgstr "" + +#: src/android/aidl/types/arrays.md +#, fuzzy +msgid "Position" +msgstr "敘述" + +#: src/android/aidl/types/arrays.md +msgid "`in` argument" +msgstr "" + +#: src/android/aidl/types/arrays.md +msgid "`&[T]`" +msgstr "`&[T]`" + +#: src/android/aidl/types/arrays.md +msgid "`out`/`inout` argument" +msgstr "" + +#: src/android/aidl/types/arrays.md +msgid "`&mut Vec`" +msgstr "`&mut Vec`" + +#: src/android/aidl/types/arrays.md +msgid "Return" +msgstr "" + +#: src/android/aidl/types/arrays.md +#: src/android/interoperability/cpp/type-mapping.md +msgid "`Vec`" +msgstr "`Vec`" + +#: src/android/aidl/types/arrays.md +msgid "" +"In Android 13 or higher, fixed-size arrays are supported, i.e. `T[N]` " +"becomes `[T; N]`. Fixed-size arrays can have multiple dimensions (e.g. " +"int\\[3\\]\\[4\\]). In the Java backend, fixed-size arrays are represented " +"as array types." +msgstr "" + +#: src/android/aidl/types/arrays.md +msgid "Arrays in parcelable fields always get translated to `Vec`." +msgstr "" + +#: src/android/aidl/types/objects.md +msgid "" +"AIDL objects can be sent either as a concrete AIDL type or as the type-" +"erased `IBinder` interface:" +msgstr "" + +#: src/android/aidl/types/objects.md +msgid "" +"**birthday_service/aidl/com/example/birthdayservice/IBirthdayInfoProvider." +"aidl**:" +msgstr "" +"**birthday_service/aidl/com/example/birthdayservice/IBirthdayInfoProvider." +"aidl**:" + +#: src/android/aidl/types/objects.md src/android/aidl/types/parcelables.md +#: src/android/aidl/types/file-descriptor.md +msgid "" +"**birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl**:" +msgstr "" +"**birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl**:" + +#: src/android/aidl/types/objects.md +msgid "/** The same thing, but using a binder object. */" +msgstr "/** The same thing, but using a binder object. */" + +#: src/android/aidl/types/objects.md +msgid "/** The same thing, but using `IBinder`. */" +msgstr "/** The same thing, but using `IBinder`. */" + +#: src/android/aidl/types/objects.md src/android/aidl/types/parcelables.md +#: src/android/aidl/types/file-descriptor.md +msgid "**birthday_service/src/client.rs**:" +msgstr "**birthday_service/src/client.rs**:" + +#: src/android/aidl/types/objects.md +msgid "/// Rust struct implementing the `IBirthdayInfoProvider` interface.\n" +msgstr "/// Rust struct implementing the `IBirthdayInfoProvider` interface.\n" + +#: src/android/aidl/types/objects.md +msgid "// Create a binder object for the `IBirthdayInfoProvider` interface.\n" +msgstr "// Create a binder object for the `IBirthdayInfoProvider` interface.\n" + +#: src/android/aidl/types/objects.md +msgid "// Send the binder object to the service.\n" +msgstr "// Send the binder object to the service.\n" + +#: src/android/aidl/types/objects.md +msgid "" +"// Perform the same operation but passing the provider as an `SpIBinder`.\n" +msgstr "" +"// Perform the same operation but passing the provider as an `SpIBinder`.\n" + +#: src/android/aidl/types/objects.md +msgid "" +"Note the usage of `BnBirthdayInfoProvider`. This serves the same purpose as " +"`BnBirthdayService` that we saw previously." +msgstr "" + +#: src/android/aidl/types/parcelables.md +msgid "Binder for Rust supports sending parcelables directly:" +msgstr "" + +#: src/android/aidl/types/parcelables.md +msgid "" +"**birthday_service/aidl/com/example/birthdayservice/BirthdayInfo.aidl**:" +msgstr "" +"**birthday_service/aidl/com/example/birthdayservice/BirthdayInfo.aidl**:" + +#: src/android/aidl/types/parcelables.md +msgid "/** The same thing, but with a parcelable. */" +msgstr "/** The same thing, but with a parcelable. */" + +#: src/android/aidl/types/file-descriptor.md +msgid "" +"Files can be sent between Binder clients/servers using the " +"`ParcelFileDescriptor` type:" +msgstr "" + +#: src/android/aidl/types/file-descriptor.md +msgid "/** The same thing, but loads info from a file. */" +msgstr "/** The same thing, but loads info from a file. */" + +#: src/android/aidl/types/file-descriptor.md +msgid "// Open a file and put the birthday info in it.\n" +msgstr "// Open a file and put the birthday info in it.\n" + +#: src/android/aidl/types/file-descriptor.md +msgid "\"/data/local/tmp/birthday.info\"" +msgstr "\"/data/local/tmp/birthday.info\"" + +#: src/android/aidl/types/file-descriptor.md +msgid "\"{name}\"" +msgstr "\"{name}\"" + +#: src/android/aidl/types/file-descriptor.md +msgid "\"{years}\"" +msgstr "\"{years}\"" + +#: src/android/aidl/types/file-descriptor.md +msgid "// Create a `ParcelFileDescriptor` from the file and send it.\n" +msgstr "// Create a `ParcelFileDescriptor` from the file and send it.\n" + +#: src/android/aidl/types/file-descriptor.md +msgid "**birthday_service/src/lib.rs**:" +msgstr "**birthday_service/src/lib.rs**:" + +#: src/android/aidl/types/file-descriptor.md +msgid "" +"// Convert the file descriptor to a `File`. `ParcelFileDescriptor` wraps\n" +" // an `OwnedFd`, which can be cloned and then used to create a " +"`File`\n" +" // object.\n" +msgstr "" +"// Convert the file descriptor to a `File`. `ParcelFileDescriptor` wraps\n" +" // an `OwnedFd`, which can be cloned and then used to create a " +"`File`\n" +" // object.\n" + +#: src/android/aidl/types/file-descriptor.md +msgid "\"Invalid file handle\"" +msgstr "" + +#: src/android/aidl/types/file-descriptor.md +msgid "" +"`ParcelFileDescriptor` wraps an `OwnedFd`, and so can be created from a " +"`File` (or any other type that wraps an `OwnedFd`), and can be used to " +"create a new `File` handle on the other side." +msgstr "" + +#: src/android/aidl/types/file-descriptor.md +msgid "" +"Other types of file descriptors can be wrapped and sent, e.g. TCP, UDP, and " +"UNIX sockets." +msgstr "" + +#: src/android/testing.md +#, fuzzy +msgid "Testing in Android" +msgstr "在 Android 中的測試" + +#: src/android/testing.md +msgid "" +"Building on [Testing](../testing.md), we will now look at how unit tests " +"work in AOSP. Use the `rust_test` module for your unit tests:" +msgstr "" + +#: src/android/testing.md +msgid "_testing/Android.bp_:" +msgstr "_testing/Android.bp_:" + +#: src/android/testing.md +msgid "\"libleftpad\"" +msgstr "\"libleftpad\"" + +#: src/android/testing.md +msgid "\"leftpad\"" +msgstr "\"leftpad\"" + +#: src/android/testing.md +msgid "\"libleftpad_test\"" +msgstr "\"libleftpad_test\"" + +#: src/android/testing.md +msgid "\"leftpad_test\"" +msgstr "\"leftpad_test\"" + +#: src/android/testing.md src/android/interoperability/with-c/bindgen.md +msgid "\"general-tests\"" +msgstr "\"general-tests\"" + +#: src/android/testing.md +msgid "_testing/src/lib.rs_:" +msgstr "_testing/src/lib.rs_:" + +#: src/android/testing.md +msgid "//! Left-padding library.\n" +msgstr "//! Left-padding library.\n" + +#: src/android/testing.md +msgid "/// Left-pad `s` to `width`.\n" +msgstr "/// Left-pad `s` to `width`.\n" + +#: src/android/testing.md +msgid "\"{s:>width$}\"" +msgstr "\"{s:>width$}\"" + +#: src/android/testing.md +msgid "\" foo\"" +msgstr "\" foo\"" + +#: src/android/testing.md +msgid "\"foobar\"" +msgstr "\"foobar\"" + +#: src/android/testing.md +#, fuzzy +msgid "You can now run the test with" +msgstr "您現在可以執行測試:" + +#: src/android/testing.md +#, fuzzy +msgid "The output looks like this:" +msgstr "整體方法大致如下:" + +#: src/android/testing.md +msgid "" +"```text\n" +"INFO: Elapsed time: 2.666s, Critical Path: 2.40s\n" +"INFO: 3 processes: 2 internal, 1 linux-sandbox.\n" +"INFO: Build completed successfully, 3 total actions\n" +"//comprehensive-rust-android/testing:libleftpad_test_host PASSED " +"in 2.3s\n" +" PASSED libleftpad_test.tests::long_string (0.0s)\n" +" PASSED libleftpad_test.tests::short_string (0.0s)\n" +"Test cases: finished with 2 passing and 0 failing out of 2 test cases\n" "```" msgstr "" -"```java\n" -"package com.example.birthdayservice;\n" -"\n" -"/** 生日功能介面 */\n" -"interface IBirthdayService {\n" -" /** 生成一段生日快樂的祝賀訊息 */\n" -" String wishHappyBirthday(String name, int years, in String[] text);\n" -"}\n" +"```text\n" +"INFO: Elapsed time: 2.666s, Critical Path: 2.40s\n" +"INFO: 3 processes: 2 internal, 1 linux-sandbox.\n" +"INFO: Build completed successfully, 3 total actions\n" +"//comprehensive-rust-android/testing:libleftpad_test_host PASSED " +"in 2.3s\n" +" PASSED libleftpad_test.tests::long_string (0.0s)\n" +" PASSED libleftpad_test.tests::short_string (0.0s)\n" +"Test cases: finished with 2 passing and 0 failing out of 2 test cases\n" "```" -#: src/android/logging.md:3 +#: src/android/testing.md +msgid "" +"Notice how you only mention the root of the library crate. Tests are found " +"recursively in nested modules." +msgstr "" + +#: src/android/testing/googletest.md +#, fuzzy +msgid "" +"The [GoogleTest](https://docs.rs/googletest/) crate allows for flexible test " +"assertions using _matchers_:" +msgstr "" +"[googletest](https://docs.rs/googletest):這是全面性的測試斷言程式庫,沿用了 " +"GoogleTest (適用於 C++) 的傳統運作方式。" + +#: src/android/testing/googletest.md +msgid "\"baz\"" +msgstr "\"baz\"" + +#: src/android/testing/googletest.md +msgid "\"xyz\"" +msgstr "\"xyz\"" + +#: src/android/testing/googletest.md +msgid "" +"If we change the last element to `\"!\"`, the test fails with a structured " +"error message pin-pointing the error:" +msgstr "" + +#: src/android/testing/googletest.md +msgid "" +"GoogleTest is not part of the Rust Playground, so you need to run this " +"example in a local environment. Use `cargo add googletest` to quickly add it " +"to an existing Cargo project." +msgstr "" + +#: src/android/testing/googletest.md +msgid "" +"The `use googletest::prelude::*;` line imports a number of [commonly used " +"macros and types](https://docs.rs/googletest/latest/googletest/prelude/index." +"html)." +msgstr "" + +#: src/android/testing/googletest.md +msgid "This just scratches the surface, there are many builtin matchers." +msgstr "" + +#: src/android/testing/googletest.md +msgid "" +"A particularly nice feature is that mismatches in multi-line strings are " +"shown as a diff:" +msgstr "" + +#: src/android/testing/googletest.md +msgid "" +"\"Memory safety found,\\n\\\n" +" Rust's strong typing guides the way,\\n\\\n" +" Secure code you'll write.\"" +msgstr "" + +#: src/android/testing/googletest.md +msgid "" +"\"Memory safety found,\\n\\\n" +" Rust's silly humor guides the way,\\n\\\n" +" Secure code you'll write.\"" +msgstr "" + +#: src/android/testing/googletest.md +msgid "shows a color-coded diff (colors not shown here):" +msgstr "" + +#: src/android/testing/googletest.md +msgid "" +"The crate is a Rust port of [GoogleTest for C++](https://google.github.io/" +"googletest/)." +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"For mocking, [Mockall](https://docs.rs/mockall/) is a widely used library. " +"You need to refactor your code to use traits, which you can then quickly " +"mock:" +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"Mockall is the recommended mocking library in Android (AOSP). There are " +"other [mocking libraries available on crates.io](https://crates.io/keywords/" +"mock), in particular in the area of mocking HTTP services. The other mocking " +"libraries work in a similar fashion as Mockall, meaning that they make it " +"easy to get a mock implementation of a given trait." +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"Note that mocking is somewhat _controversial_: mocks allow you to completely " +"isolate a test from its dependencies. The immediate result is faster and " +"more stable test execution. On the other hand, the mocks can be configured " +"wrongly and return output different from what the real dependencies would do." +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"If at all possible, it is recommended that you use the real dependencies. As " +"an example, many databases allow you to configure an in-memory backend. This " +"means that you get the correct behavior in your tests, plus they are fast " +"and will automatically clean up after themselves." +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"Similarly, many web frameworks allow you to start an in-process server which " +"binds to a random port on `localhost`. Always prefer this over mocking away " +"the framework since it helps you test your code in the real environment." +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"Mockall is not part of the Rust Playground, so you need to run this example " +"in a local environment. Use `cargo add mockall` to quickly add Mockall to an " +"existing Cargo project." +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"Mockall has a lot more functionality. In particular, you can set up " +"expectations which depend on the arguments passed. Here we use this to mock " +"a cat which becomes hungry 3 hours after the last time it was fed:" +msgstr "" + +#: src/android/testing/mocking.md +msgid "" +"You can use `.times(n)` to limit the number of times a mock method can be " +"called to `n` --- the mock will automatically panic when dropped if this " +"isn't satisfied." +msgstr "" + +#: src/android/logging.md msgid "" "You should use the `log` crate to automatically log to `logcat` (on-device) " "or `stdout` (on-host):" msgstr "" +"您應使用 `log` Crate,自動將記錄印出到 `logcat` (裝置端) 或 `stdout` (主機" +"端):" -#: src/android/logging.md:6 +#: src/android/logging.md msgid "_hello_rust_logs/Android.bp_:" -msgstr "" +msgstr "_hello_rust_logs/Android.bp_:" -#: src/android/logging.md:8 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"hello_rust_logs\",\n" -" crate_name: \"hello_rust_logs\",\n" -" srcs: [\"src/main.rs\"],\n" -" rustlibs: [\n" -" \"liblog_rust\",\n" -" \"liblogger\",\n" -" ],\n" -" prefer_rlib: true,\n" -" host_supported: true,\n" -"}\n" -"```" -msgstr "" +#: src/android/logging.md +msgid "\"hello_rust_logs\"" +msgstr "\"hello_rust_logs\"" -#: src/android/logging.md:22 +#: src/android/logging.md +msgid "\"liblog_rust\"" +msgstr "\"liblog_rust\"" + +#: src/android/logging.md +msgid "\"liblogger\"" +msgstr "\"liblogger\"" + +#: src/android/logging.md msgid "_hello_rust_logs/src/main.rs_:" -msgstr "" +msgstr "_hello_rust_logs/src/main.rs_:" -#: src/android/logging.md:24 -msgid "" -"```rust,ignore\n" -"//! Rust logging demo.\n" -"\n" -"use log::{debug, error, info};\n" -"\n" -"/// Logs a greeting.\n" -"fn main() {\n" -" logger::init(\n" -" logger::Config::default()\n" -" .with_tag_on_device(\"rust\")\n" -" .with_min_level(log::Level::Trace),\n" -" );\n" -" debug!(\"Starting program.\");\n" -" info!(\"Things are going fine.\");\n" -" error!(\"Something went wrong!\");\n" -"}\n" -"```" -msgstr "" +#: src/android/logging.md +msgid "//! Rust logging demo.\n" +msgstr "//! Rust logging demo.\n" -#: src/android/logging.md:42 src/android/interoperability/with-c/bindgen.md:98 -#: src/android/interoperability/with-c/rust.md:73 +#: src/android/logging.md +msgid "/// Logs a greeting.\n" +msgstr "/// Logs a greeting.\n" + +#: src/android/logging.md +msgid "\"rust\"" +msgstr "\"rust\"" + +#: src/android/logging.md +msgid "\"Starting program.\"" +msgstr "\"Starting program.\"" + +#: src/android/logging.md +msgid "\"Things are going fine.\"" +msgstr "\"Things are going fine.\"" + +#: src/android/logging.md +msgid "\"Something went wrong!\"" +msgstr "\"Something went wrong!\"" + +#: src/android/logging.md src/android/interoperability/with-c/bindgen.md +#: src/android/interoperability/with-c/rust.md msgid "Build, push, and run the binary on your device:" -msgstr "" +msgstr "建構、推送及在裝置上執行二進位檔:" -#: src/android/logging.md:44 +#: src/android/logging.md msgid "" "```shell\n" -"$ m hello_rust_logs\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_logs /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/hello_rust_logs\n" +"m hello_rust_logs\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_logs\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/hello_rust_logs\n" "```" msgstr "" +"```shell\n" +"m hello_rust_logs\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/hello_rust_logs\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/hello_rust_logs\n" +"```" -#: src/android/logging.md:50 +#: src/android/logging.md msgid "The logs show up in `adb logcat`:" -msgstr "" +msgstr "記錄會顯示在 `adb logcat` 中:" -#: src/android/logging.md:52 -msgid "" -"```shell\n" -"$ adb logcat -s rust\n" -"09-08 08:38:32.454 2420 2420 D rust: hello_rust_logs: Starting program.\n" -"09-08 08:38:32.454 2420 2420 I rust: hello_rust_logs: Things are going " -"fine.\n" -"09-08 08:38:32.454 2420 2420 E rust: hello_rust_logs: Something went " -"wrong!\n" -"```" -msgstr "" - -#: src/android/interoperability.md:3 +#: src/android/interoperability.md msgid "" "Rust has excellent support for interoperability with other languages. This " "means that you can:" -msgstr "" +msgstr "Rust 能充分支援與其他程式語言互通。也就是說,您可以:" -#: src/android/interoperability.md:6 +#: src/android/interoperability.md msgid "Call Rust functions from other languages." -msgstr "" +msgstr "透過其他語言呼叫 Rust 函式。" -#: src/android/interoperability.md:7 +#: src/android/interoperability.md msgid "Call functions written in other languages from Rust." -msgstr "" +msgstr "透過 Rust 呼叫以其他語言編寫的函式。" -#: src/android/interoperability.md:9 +#: src/android/interoperability.md msgid "" "When you call functions in a foreign language we say that you're using a " "_foreign function interface_, also known as FFI." msgstr "" +"當您以其他語言呼叫函式時,我們稱之為使用「_外部函式介面_」,亦稱 FFI " +"(Foreign Function Interface)。" -#: src/android/interoperability/with-c.md:1 +#: src/android/interoperability/with-c.md msgid "Interoperability with C" -msgstr "" +msgstr "與 C 的互通性" -#: src/android/interoperability/with-c.md:3 +#: src/android/interoperability/with-c.md msgid "" "Rust has full support for linking object files with a C calling convention. " "Similarly, you can export Rust functions and call them from C." msgstr "" +"Rust 能完整支援以 C 語言的呼叫慣例來連結物件檔案。同樣地,您可以匯出 Rust 函" +"式,然後透過 C 語言呼叫這些函式。" -#: src/android/interoperability/with-c.md:6 +#: src/android/interoperability/with-c.md msgid "You can do it by hand if you want:" -msgstr "" +msgstr "您可以視需要手動完成操作:" -#: src/android/interoperability/with-c.md:8 -msgid "" -"```rust\n" -"extern \"C\" {\n" -" fn abs(x: i32) -> i32;\n" -"}\n" -"\n" -"fn main() {\n" -" let x = -42;\n" -" let abs_x = unsafe { abs(x) };\n" -" println!(\"{x}, {abs_x}\");\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c.md +msgid "\"{x}, {abs_x}\"" +msgstr "\"{x}, {abs_x}\"" -#: src/android/interoperability/with-c.md:20 +#: src/android/interoperability/with-c.md msgid "" "We already saw this in the [Safe FFI Wrapper exercise](../../exercises/day-3/" "safe-ffi-wrapper.md)." msgstr "" +"我們已在[「安全的 FFI 包裝函式」練習](../../exercises/day-3/safe-ffi-wrapper." +"md)中看過此例。" -#: src/android/interoperability/with-c.md:23 +#: src/android/interoperability/with-c.md msgid "" "This assumes full knowledge of the target platform. Not recommended for " "production." -msgstr "" +msgstr "執行這項操作的前提是要充分瞭解目標平台。此法不建議用於正式環境。" -#: src/android/interoperability/with-c.md:26 +#: src/android/interoperability/with-c.md msgid "We will look at better options next." -msgstr "" +msgstr "我們接下來會討論更好的選項。" -#: src/android/interoperability/with-c/bindgen.md:1 +#: src/android/interoperability/with-c/bindgen.md msgid "Using Bindgen" -msgstr "" +msgstr "使用 Bindgen" -#: src/android/interoperability/with-c/bindgen.md:3 +#: src/android/interoperability/with-c/bindgen.md msgid "" "The [bindgen](https://rust-lang.github.io/rust-bindgen/introduction.html) " "tool can auto-generate bindings from a C header file." msgstr "" +"[bindgen](https://rust-lang.github.io/rust-bindgen/introduction.html) 工具可" +"從 C 標頭檔案自動產生繫結。" -#: src/android/interoperability/with-c/bindgen.md:6 +#: src/android/interoperability/with-c/bindgen.md msgid "First create a small C library:" -msgstr "" +msgstr "首先,請建立小型 C 程式庫:" -#: src/android/interoperability/with-c/bindgen.md:8 +#: src/android/interoperability/with-c/bindgen.md msgid "_interoperability/bindgen/libbirthday.h_:" -msgstr "" +msgstr "__interoperability/bindgen/libbirthday.h:" -#: src/android/interoperability/with-c/bindgen.md:10 -msgid "" -"```c\n" -"typedef struct card {\n" -" const char* name;\n" -" int years;\n" -"} card;\n" -"\n" -"void print_card(const card* card);\n" -"```" -msgstr "" - -#: src/android/interoperability/with-c/bindgen.md:19 +#: src/android/interoperability/with-c/bindgen.md msgid "_interoperability/bindgen/libbirthday.c_:" -msgstr "" +msgstr "__interoperability/bindgen/libbirthday.c:" -#: src/android/interoperability/with-c/bindgen.md:21 -msgid "" -"```c\n" -"#include \n" -"#include \"libbirthday.h\"\n" -"\n" -"void print_card(const card* card) {\n" -" printf(\"+--------------\\n\");\n" -" printf(\"| Happy Birthday %s!\\n\", card->name);\n" -" printf(\"| Congratulations with the %i years!\\n\", card->years);\n" -" printf(\"+--------------\\n\");\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "" +msgstr "" -#: src/android/interoperability/with-c/bindgen.md:33 +#: src/android/interoperability/with-c/bindgen.md +msgid "\"libbirthday.h\"" +msgstr "\"libbirthday.h\"" + +#: src/android/interoperability/with-c/bindgen.md +msgid "\"+--------------\\n\"" +msgstr "\"+--------------\\n\"" + +#: src/android/interoperability/with-c/bindgen.md +msgid "\"| Happy Birthday %s!\\n\"" +msgstr "\"| Happy Birthday %s!\\n\"" + +#: src/android/interoperability/with-c/bindgen.md +msgid "\"| Congratulations with the %i years!\\n\"" +msgstr "\"| Congratulations with the %i years!\\n\"" + +#: src/android/interoperability/with-c/bindgen.md msgid "Add this to your `Android.bp` file:" -msgstr "" +msgstr "請將以下內容加入 `Android.bp` 檔案:" -#: src/android/interoperability/with-c/bindgen.md:35 -#: src/android/interoperability/with-c/bindgen.md:55 -#: src/android/interoperability/with-c/bindgen.md:69 -#: src/android/interoperability/with-c/bindgen.md:108 +#: src/android/interoperability/with-c/bindgen.md msgid "_interoperability/bindgen/Android.bp_:" -msgstr "" +msgstr "__interoperability/bindgen/Android.bp:" -#: src/android/interoperability/with-c/bindgen.md:37 -msgid "" -"```javascript\n" -"cc_library {\n" -" name: \"libbirthday\",\n" -" srcs: [\"libbirthday.c\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "\"libbirthday\"" +msgstr "\"libbirthday\"" -#: src/android/interoperability/with-c/bindgen.md:44 +#: src/android/interoperability/with-c/bindgen.md +msgid "\"libbirthday.c\"" +msgstr "\"libbirthday.c\"" + +#: src/android/interoperability/with-c/bindgen.md msgid "" "Create a wrapper header file for the library (not strictly needed in this " "example):" -msgstr "" +msgstr "為程式庫建立包裝函式標頭檔案 (在此範例中不一定需要):" -#: src/android/interoperability/with-c/bindgen.md:47 +#: src/android/interoperability/with-c/bindgen.md msgid "_interoperability/bindgen/libbirthday_wrapper.h_:" -msgstr "" +msgstr "__interoperability/bindgen/libbirthday_wrapper.h:" -#: src/android/interoperability/with-c/bindgen.md:49 -msgid "" -"```c\n" -"#include \"libbirthday.h\"\n" -"```" -msgstr "" - -#: src/android/interoperability/with-c/bindgen.md:53 +#: src/android/interoperability/with-c/bindgen.md msgid "You can now auto-generate the bindings:" -msgstr "" +msgstr "您現在可以自動產生繫結:" -#: src/android/interoperability/with-c/bindgen.md:57 -msgid "" -"```javascript\n" -"rust_bindgen {\n" -" name: \"libbirthday_bindgen\",\n" -" crate_name: \"birthday_bindgen\",\n" -" wrapper_src: \"libbirthday_wrapper.h\",\n" -" source_stem: \"bindings\",\n" -" static_libs: [\"libbirthday\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "\"libbirthday_bindgen\"" +msgstr "\"libbirthday_bindgen\"" -#: src/android/interoperability/with-c/bindgen.md:67 +#: src/android/interoperability/with-c/bindgen.md +#, fuzzy +msgid "\"birthday_bindgen\"" +msgstr "\"libbirthday_bindgen\"" + +#: src/android/interoperability/with-c/bindgen.md +msgid "\"libbirthday_wrapper.h\"" +msgstr "\"libbirthday_wrapper.h\"" + +#: src/android/interoperability/with-c/bindgen.md +msgid "\"bindings\"" +msgstr "\"bindings\"" + +#: src/android/interoperability/with-c/bindgen.md msgid "Finally, we can use the bindings in our Rust program:" -msgstr "" +msgstr "最後,我們可以在 Rust 程式中使用繫結:" -#: src/android/interoperability/with-c/bindgen.md:71 -msgid "" -"```javascript\n" -"rust_binary {\n" -" name: \"print_birthday_card\",\n" -" srcs: [\"main.rs\"],\n" -" rustlibs: [\"libbirthday_bindgen\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "\"print_birthday_card\"" +msgstr "\"print_birthday_card\"" -#: src/android/interoperability/with-c/bindgen.md:79 +#: src/android/interoperability/with-c/bindgen.md +msgid "\"main.rs\"" +msgstr "\"main.rs\"" + +#: src/android/interoperability/with-c/bindgen.md msgid "_interoperability/bindgen/main.rs_:" -msgstr "" +msgstr "__interoperability/bindgen/main.rs:" -#: src/android/interoperability/with-c/bindgen.md:81 -msgid "" -"```rust,compile_fail\n" -"//! Bindgen demo.\n" -"\n" -"use birthday_bindgen::{card, print_card};\n" -"\n" -"fn main() {\n" -" let name = std::ffi::CString::new(\"Peter\").unwrap();\n" -" let card = card {\n" -" name: name.as_ptr(),\n" -" years: 42,\n" -" };\n" -" unsafe {\n" -" print_card(&card as *const card);\n" -" }\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "//! Bindgen demo.\n" +msgstr "//! Bindgen demo.\n" -#: src/android/interoperability/with-c/bindgen.md:100 +#: src/android/interoperability/with-c/bindgen.md +msgid "// SAFETY: `print_card` is safe to call with a valid `card` pointer.\n" +msgstr "// SAFETY: `print_card` is safe to call with a valid `card` pointer.\n" + +#: src/android/interoperability/with-c/bindgen.md msgid "" "```shell\n" -"$ m print_birthday_card\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/print_birthday_card /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/print_birthday_card\n" +"m print_birthday_card\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/print_birthday_card\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/print_birthday_card\n" "```" msgstr "" +"```shell\n" +"m print_birthday_card\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/print_birthday_card\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/print_birthday_card\n" +"```" -#: src/android/interoperability/with-c/bindgen.md:106 +#: src/android/interoperability/with-c/bindgen.md msgid "Finally, we can run auto-generated tests to ensure the bindings work:" -msgstr "" +msgstr "最後,我們可以執行自動產生的測試,確保繫結正常運作:" -#: src/android/interoperability/with-c/bindgen.md:110 -msgid "" -"```javascript\n" -"rust_test {\n" -" name: \"libbirthday_bindgen_test\",\n" -" srcs: [\":libbirthday_bindgen\"],\n" -" crate_name: \"libbirthday_bindgen_test\",\n" -" test_suites: [\"general-tests\"],\n" -" auto_gen_config: true,\n" -" clippy_lints: \"none\", // Generated file, skip linting\n" -" lints: \"none\",\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "\"libbirthday_bindgen_test\"" +msgstr "\"libbirthday_bindgen_test\"" -#: src/android/interoperability/with-c/bindgen.md:122 -msgid "" -"```shell\n" -"$ atest libbirthday_bindgen_test\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/bindgen.md +msgid "\":libbirthday_bindgen\"" +msgstr "\":libbirthday_bindgen\"" -#: src/android/interoperability/with-c/rust.md:1 +#: src/android/interoperability/with-c/bindgen.md +msgid "\"none\"" +msgstr "\"none\"" + +#: src/android/interoperability/with-c/bindgen.md +msgid "// Generated file, skip linting\n" +msgstr "// Generated file, skip linting\n" + +#: src/android/interoperability/with-c/rust.md msgid "Calling Rust" -msgstr "" +msgstr "呼叫 Rust" -#: src/android/interoperability/with-c/rust.md:3 +#: src/android/interoperability/with-c/rust.md msgid "Exporting Rust functions and types to C is easy:" -msgstr "" +msgstr "您可以輕鬆將 Rust 函式和型別匯出至 C:" -#: src/android/interoperability/with-c/rust.md:5 +#: src/android/interoperability/with-c/rust.md msgid "_interoperability/rust/libanalyze/analyze.rs_" -msgstr "" +msgstr "__interoperability/rust/libanalyze/analyze.rs" -#: src/android/interoperability/with-c/rust.md:7 -msgid "" -"```rust,editable\n" -"//! Rust FFI demo.\n" -"#![deny(improper_ctypes_definitions)]\n" -"\n" -"use std::os::raw::c_int;\n" -"\n" -"/// Analyze the numbers.\n" -"#[no_mangle]\n" -"pub extern \"C\" fn analyze_numbers(x: c_int, y: c_int) {\n" -" if x < y {\n" -" println!(\"x ({x}) is smallest!\");\n" -" } else {\n" -" println!(\"y ({y}) is probably larger than x ({x})\");\n" -" }\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/rust.md +msgid "//! Rust FFI demo.\n" +msgstr "//! Rust FFI demo.\n" -#: src/android/interoperability/with-c/rust.md:24 +#: src/android/interoperability/with-c/rust.md +msgid "/// Analyze the numbers.\n" +msgstr "/// Analyze the numbers.\n" + +#: src/android/interoperability/with-c/rust.md +msgid "\"x ({x}) is smallest!\"" +msgstr "\"x ({x}) is smallest!\"" + +#: src/android/interoperability/with-c/rust.md +msgid "\"y ({y}) is probably larger than x ({x})\"" +msgstr "\"y ({y}) is probably larger than x ({x})\"" + +#: src/android/interoperability/with-c/rust.md msgid "_interoperability/rust/libanalyze/analyze.h_" -msgstr "" +msgstr "__interoperability/rust/libanalyze/analyze.h" -#: src/android/interoperability/with-c/rust.md:26 -msgid "" -"```c\n" -"#ifndef ANALYSE_H\n" -"#define ANALYSE_H\n" -"\n" -"extern \"C\" {\n" -"void analyze_numbers(int x, int y);\n" -"}\n" -"\n" -"#endif\n" -"```" -msgstr "" - -#: src/android/interoperability/with-c/rust.md:37 +#: src/android/interoperability/with-c/rust.md msgid "_interoperability/rust/libanalyze/Android.bp_" -msgstr "" +msgstr "__interoperability/rust/libanalyze/Android.bp" -#: src/android/interoperability/with-c/rust.md:39 -msgid "" -"```javascript\n" -"rust_ffi {\n" -" name: \"libanalyze_ffi\",\n" -" crate_name: \"analyze_ffi\",\n" -" srcs: [\"analyze.rs\"],\n" -" include_dirs: [\".\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/rust.md +msgid "\"libanalyze_ffi\"" +msgstr "\"libanalyze_ffi\"" -#: src/android/interoperability/with-c/rust.md:48 +#: src/android/interoperability/with-c/rust.md +msgid "\"analyze_ffi\"" +msgstr "\"analyze_ffi\"" + +#: src/android/interoperability/with-c/rust.md +msgid "\"analyze.rs\"" +msgstr "\"analyze.rs\"" + +#: src/android/interoperability/with-c/rust.md msgid "We can now call this from a C binary:" -msgstr "" +msgstr "我們現在可以從 C 二進位檔呼叫此介面:" -#: src/android/interoperability/with-c/rust.md:50 +#: src/android/interoperability/with-c/rust.md msgid "_interoperability/rust/analyze/main.c_" -msgstr "" +msgstr "__interoperability/rust/analyze/main.c" -#: src/android/interoperability/with-c/rust.md:52 -msgid "" -"```c\n" -"#include \"analyze.h\"\n" -"\n" -"int main() {\n" -" analyze_numbers(10, 20);\n" -" analyze_numbers(123, 123);\n" -" return 0;\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/rust.md +msgid "\"analyze.h\"" +msgstr "\"analyze.h\"" -#: src/android/interoperability/with-c/rust.md:62 +#: src/android/interoperability/with-c/rust.md msgid "_interoperability/rust/analyze/Android.bp_" -msgstr "" +msgstr "__interoperability/rust/analyze/Android.bp" -#: src/android/interoperability/with-c/rust.md:64 -msgid "" -"```javascript\n" -"cc_binary {\n" -" name: \"analyze_numbers\",\n" -" srcs: [\"main.c\"],\n" -" static_libs: [\"libanalyze_ffi\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/with-c/rust.md +msgid "\"analyze_numbers\"" +msgstr "\"analyze_numbers\"" -#: src/android/interoperability/with-c/rust.md:75 +#: src/android/interoperability/with-c/rust.md +msgid "\"main.c\"" +msgstr "\"main.c\"" + +#: src/android/interoperability/with-c/rust.md msgid "" "```shell\n" -"$ m analyze_numbers\n" -"$ adb push \"$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers /data/local/" -"tmp\"\n" -"$ adb shell /data/local/tmp/analyze_numbers\n" +"m analyze_numbers\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/analyze_numbers\n" "```" msgstr "" +"```shell\n" +"m analyze_numbers\n" +"adb push \"$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers\" /data/local/" +"tmp\n" +"adb shell /data/local/tmp/analyze_numbers\n" +"```" -#: src/android/interoperability/with-c/rust.md:83 +#: src/android/interoperability/with-c/rust.md msgid "" "`#[no_mangle]` disables Rust's usual name mangling, so the exported symbol " "will just be the name of the function. You can also use `#[export_name = " "\"some_name\"]` to specify whatever name you want." msgstr "" +"`#[no_mangle]` 會停用 Rust 的一般名稱改編功能,因此匯出的符號將只是函式名稱。" +"您也可以使用 `#[export_name = \"some_name\"]` 指定任何名稱。" -#: src/android/interoperability/cpp.md:3 +#: src/android/interoperability/cpp.md msgid "" "The [CXX crate](https://cxx.rs/) makes it possible to do safe " "interoperability between Rust and C++." msgstr "" +"透過 [CXX Crate](https://cxx.rs/),您可以在 Rust 和 C++ 之間實現安全的互通" +"性。" -#: src/android/interoperability/cpp.md:6 +#: src/android/interoperability/cpp.md msgid "The overall approach looks like this:" -msgstr "" +msgstr "整體方法大致如下:" -#: src/android/interoperability/cpp.md:10 +#: src/android/interoperability/cpp/bridge.md msgid "" -"See the [CXX tutorial](https://cxx.rs/tutorial.html) for an full example of " -"using this." +"CXX relies on a description of the function signatures that will be exposed " +"from each language to the other. You provide this description using extern " +"blocks in a Rust module annotated with the `#[cxx::bridge]` attribute macro." msgstr "" +"CXX 的運作需要依照函式的型別敘述。這些敘述定義了從一種語言公開至另一種語言的" +"介面。您會在具有 `#[cxx::bridge]` 屬性巨集註解的 Rust 模組中,使用外部區塊提" +"供這項說明。" -#: src/android/interoperability/java.md:1 +#: src/android/interoperability/cpp/bridge.md +msgid "\"org::blobstore\"" +msgstr "\"org::blobstore\"" + +#: src/android/interoperability/cpp/bridge.md +msgid "// Shared structs with fields visible to both languages.\n" +msgstr "// Shared structs with fields visible to both languages.\n" + +#: src/android/interoperability/cpp/bridge.md +#: src/android/interoperability/cpp/generated-cpp.md +msgid "// Rust types and signatures exposed to C++.\n" +msgstr "// Rust types and signatures exposed to C++.\n" + +#: src/android/interoperability/cpp/bridge.md +#: src/android/interoperability/cpp/rust-bridge.md +#: src/android/interoperability/cpp/generated-cpp.md +#: src/android/interoperability/cpp/rust-result.md +#: src/chromium/interoperability-with-cpp/example-bindings.md +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "\"Rust\"" +msgstr "\"Rust\"" + +#: src/android/interoperability/cpp/bridge.md +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "// C++ types and signatures exposed to Rust.\n" +msgstr "// C++ types and signatures exposed to Rust.\n" + +#: src/android/interoperability/cpp/bridge.md +#: src/android/interoperability/cpp/cpp-bridge.md +#: src/android/interoperability/cpp/cpp-exception.md +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "\"C++\"" +msgstr "\"C++\"" + +#: src/android/interoperability/cpp/bridge.md +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "\"include/blobstore.h\"" +msgstr "\"include/blobstore.h\"" + +#: src/android/interoperability/cpp/bridge.md +msgid "The bridge is generally declared in an `ffi` module within your crate." +msgstr "橋接器通常是在 Crate 中的 `ffi` 模組中宣告。" + +#: src/android/interoperability/cpp/bridge.md +msgid "" +"From the declarations made in the bridge module, CXX will generate matching " +"Rust and C++ type/function definitions in order to expose those items to " +"both languages." +msgstr "" +"透過在橋接模組中建立宣告,CXX 會產生相符的 Rust 和 C++ 型別/函式定義,以便向" +"這兩種語言公開這些項目。" + +#: src/android/interoperability/cpp/bridge.md +msgid "" +"To view the generated Rust code, use [cargo-expand](https://github.com/" +"dtolnay/cargo-expand) to view the expanded proc macro. For most of the " +"examples you would use `cargo expand ::ffi` to expand just the `ffi` module " +"(though this doesn't apply for Android projects)." +msgstr "" +"如要查看產生的 Rust 程式碼,請使用 [cargo-expand](https://github.com/dtolnay/" +"cargo-expand) 檢視已展開的程序巨集。在大多數範例中,您都會使用 `cargo " +"expand ::ffi`,這樣就能只展開 `ffi` 模組 (但這不適用於 Android 專案)。" + +#: src/android/interoperability/cpp/bridge.md +msgid "To view the generated C++ code, look in `target/cxxbridge`." +msgstr "如要檢視產生的 C++ 程式碼,請查看 `target/cxxbridge`。" + +#: src/android/interoperability/cpp/rust-bridge.md +msgid "Rust Bridge Declarations" +msgstr "Rust 橋接器宣告" + +#: src/android/interoperability/cpp/rust-bridge.md +msgid "// Opaque type\n" +msgstr "// Opaque type\n" + +#: src/android/interoperability/cpp/rust-bridge.md +msgid "// Method on `MyType`\n" +msgstr "// Method on `MyType`\n" + +#: src/android/interoperability/cpp/rust-bridge.md +msgid "// Free function\n" +msgstr "// Free function\n" + +#: src/android/interoperability/cpp/rust-bridge.md +msgid "" +"Items declared in the `extern \"Rust\"` reference items that are in scope in " +"the parent module." +msgstr "在 `extern \"Rust\"` 參照項目中宣告的項目皆位於上層模組的範圍。" + +#: src/android/interoperability/cpp/rust-bridge.md +msgid "" +"The CXX code generator uses your `extern \"Rust\"` section(s) to produce a C+" +"+ header file containing the corresponding C++ declarations. The generated " +"header has the same path as the Rust source file containing the bridge, " +"except with a .rs.h file extension." +msgstr "" +"CXX 程式碼產生器會使用您的 `extern \"Rust\"` 區段,產生含有相對應 C++ 宣告的 " +"C++ 標頭檔案。產生的標頭與包含橋接器的 Rust 來源檔案具有相同路徑,但副檔名" +"為 .rs.h。" + +#: src/android/interoperability/cpp/generated-cpp.md +msgid "Results in (roughly) the following C++:" +msgstr "(大致) 產生下列 C++:" + +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "C++ Bridge Declarations" +msgstr "C++ 橋接器宣告" + +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "Results in (roughly) the following Rust:" +msgstr "(大致) 產生下列 Rust:" + +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "\"org$blobstore$cxxbridge1$new_blobstore_client\"" +msgstr "\"org$blobstore$cxxbridge1$new_blobstore_client\"" + +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "\"org$blobstore$cxxbridge1$BlobstoreClient$put\"" +msgstr "\"org$blobstore$cxxbridge1$BlobstoreClient$put\"" + +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "" +"The programmer does not need to promise that the signatures they have typed " +"in are accurate. CXX performs static assertions that the signatures exactly " +"correspond with what is declared in C++." +msgstr "" +"程式設計師不需要保證已輸入的簽章正確無誤。CXX 會執行靜態斷言,保證簽章與 C++ " +"中宣告的內容完全相符。" + +#: src/android/interoperability/cpp/cpp-bridge.md +msgid "" +"`unsafe extern` blocks allow you to declare C++ functions that are safe to " +"call from Rust." +msgstr "`unsafe extern` 區塊可用來宣告能從 Rust 安全呼叫的 C++ 函式。" + +#: src/android/interoperability/cpp/shared-types.md +msgid "// A=1, J=11, Q=12, K=13\n" +msgstr "// A=1, J=11, Q=12, K=13\n" + +#: src/android/interoperability/cpp/shared-types.md +msgid "Only C-like (unit) enums are supported." +msgstr "只支援與 C 類似的 (單元) 列舉。" + +#: src/android/interoperability/cpp/shared-types.md +msgid "" +"A limited number of traits are supported for `#[derive()]` on shared types. " +"Corresponding functionality is also generated for the C++ code, e.g. if you " +"derive `Hash` also generates an implementation of `std::hash` for the " +"corresponding C++ type." +msgstr "" +"共用型別上的 `#[derive()]` 只支援部分特徵。系統也會為 C++ 程式碼產生相對應的" +"功能。舉例來說,如果衍生出 `Hash`,也會為相應的 C++ 型別產生 `std::hash` 的實" +"作項目。" + +#: src/android/interoperability/cpp/shared-enums.md +msgid "Generated Rust:" +msgstr "產生的 Rust:" + +#: src/android/interoperability/cpp/shared-enums.md +msgid "Generated C++:" +msgstr "產生的 C++:" + +#: src/android/interoperability/cpp/shared-enums.md +msgid "" +"On the Rust side, the code generated for shared enums is actually a struct " +"wrapping a numeric value. This is because it is not UB in C++ for an enum " +"class to hold a value different from all of the listed variants, and our " +"Rust representation needs to have the same behavior." +msgstr "" +"在 Rust 端,為共用列舉產生的程式碼其實是包裝數值的結構體。這是因為在 C++ 中," +"列舉類別保留與所有所列變數不同的值並不屬於 UB,而 Rust 表示法需具有相同行為。" + +#: src/android/interoperability/cpp/rust-result.md +msgid "\"fallible1 requires depth > 0\"" +msgstr "\"fallible1 requires depth > 0\"" + +#: src/android/interoperability/cpp/rust-result.md +msgid "\"Success!\"" +msgstr "\"Success!\"" + +#: src/android/interoperability/cpp/rust-result.md +msgid "" +"Rust functions that return `Result` are translated to exceptions on the C++ " +"side." +msgstr "傳回 `Result` 的 Rust 函式會轉譯為 C++ 端的例外狀況。" + +#: src/android/interoperability/cpp/rust-result.md +msgid "" +"The exception thrown will always be of type `rust::Error`, which primarily " +"exposes a way to get the error message string. The error message will come " +"from the error type's `Display` impl." +msgstr "" +"擲回的例外狀況一律屬於 `rust::Error` 類型,這主要用來公開取得錯誤訊息字串的方" +"法。錯誤訊息會來自錯誤類型的 `Display` 實作項目。" + +#: src/android/interoperability/cpp/rust-result.md +msgid "" +"A panic unwinding from Rust to C++ will always cause the process to " +"immediately terminate." +msgstr "從 Rust 恐慌解開至 C++ 一律會導致程序立即終止。" + +#: src/android/interoperability/cpp/cpp-exception.md +msgid "\"example/include/example.h\"" +msgstr "\"example/include/example.h\"" + +#: src/android/interoperability/cpp/cpp-exception.md +msgid "\"Error: {}\"" +msgstr "\"Error: {}\"" + +#: src/android/interoperability/cpp/cpp-exception.md +msgid "" +"C++ functions declared to return a `Result` will catch any thrown exception " +"on the C++ side and return it as an `Err` value to the calling Rust function." +msgstr "" +"所宣告用來傳回 `Result` 的 C++ 函式會擷取 C++ 端的任何擲回例外狀況,並將其當" +"做 `Err` 值傳回至發出呼叫的 Rust 函式。" + +#: src/android/interoperability/cpp/cpp-exception.md +msgid "" +"If an exception is thrown from an extern \"C++\" function that is not " +"declared by the CXX bridge to return `Result`, the program calls C++'s `std::" +"terminate`. The behavior is equivalent to the same exception being thrown " +"through a `noexcept` C++ function." +msgstr "" +"假使例外狀況是從 CXX 橋接器未宣告的外部「C++」函式擲回,藉此傳回 `Result`,則" +"程式會呼叫 C++ 的 `std::terminate`。此行為等同於透過 `noexcept` C++ 函式擲回" +"的相同例外狀況。" + +#: src/android/interoperability/cpp/type-mapping.md +#, fuzzy +msgid "C++ Type" +msgstr "C++ 範例" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`rust::String`" +msgstr "`rust::String`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`&str`" +msgstr "`&str`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`rust::Str`" +msgstr "`rust::Str`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`CxxString`" +msgstr "`CxxString`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`std::string`" +msgstr "`std::string`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`&[T]`/`&mut [T]`" +msgstr "`&[T]`/`&mut [T]`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`rust::Slice`" +msgstr "`rust::Slice`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`rust::Box`" +msgstr "`rust::Box`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`UniquePtr`" +msgstr "`UniquePtr`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`std::unique_ptr`" +msgstr "`std::unique_ptr`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`rust::Vec`" +msgstr "`rust::Vec`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`CxxVector`" +msgstr "`CxxVector`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "`std::vector`" +msgstr "`std::vector`" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "" +"These types can be used in the fields of shared structs and the arguments " +"and returns of extern functions." +msgstr "這些型別可用於共用結構體的欄位,以及外部函式的引數和回傳內容。" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "" +"Note that Rust's `String` does not map directly to `std::string`. There are " +"a few reasons for this:" +msgstr "" +"請注意,Rust 的 `String` 不會直接對應至 `std::string`。以下列舉幾個原因:" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "" +"`std::string` does not uphold the UTF-8 invariant that `String` requires." +msgstr "`std::string` 不會維護 `String` 所需的 UTF-8 不變體。" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "" +"The two types have different layouts in memory and so can't be passed " +"directly between languages." +msgstr "這兩種型別的內部記憶體結構不同,因此無法在語言之間直接傳遞。" + +#: src/android/interoperability/cpp/type-mapping.md +msgid "" +"`std::string` requires move constructors that don't match Rust's move " +"semantics, so a `std::string` can't be passed by value to Rust." +msgstr "" +"`std::string` 需要的移動建構函式與 Rust 的移動語意不相符,因此 `std::string` " +"無法透過值傳遞至 Rust。" + +#: src/android/interoperability/cpp/android-build-cpp.md +#: src/android/interoperability/cpp/android-cpp-genrules.md +#: src/android/interoperability/cpp/android-build-rust.md +msgid "Building in Android" +msgstr "在 Android 中建構" + +#: src/android/interoperability/cpp/android-build-cpp.md +msgid "" +"Create a `cc_library_static` to build the C++ library, including the CXX " +"generated header and source file." +msgstr "" +"建立 `cc_library_static` 來建構 C++ 程式庫,包括 CXX 產生的標頭檔案和來源檔" +"案。" + +#: src/android/interoperability/cpp/android-build-cpp.md +#: src/android/interoperability/cpp/android-build-rust.md +msgid "\"libcxx_test_cpp\"" +msgstr "\"libcxx_test_cpp\"" + +#: src/android/interoperability/cpp/android-build-cpp.md +msgid "\"cxx_test.cpp\"" +msgstr "\"cxx_test.cpp\"" + +#: src/android/interoperability/cpp/android-build-cpp.md +msgid "\"cxx-bridge-header\"" +msgstr "\"cxx-bridge-header\"" + +#: src/android/interoperability/cpp/android-build-cpp.md +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"libcxx_test_bridge_header\"" +msgstr "\"libcxx_test_bridge_header\"" + +#: src/android/interoperability/cpp/android-build-cpp.md +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"libcxx_test_bridge_code\"" +msgstr "\"libcxx_test_bridge_code\"" + +#: src/android/interoperability/cpp/android-build-cpp.md +msgid "" +"Point out that `libcxx_test_bridge_header` and `libcxx_test_bridge_code` are " +"the dependencies for the CXX-generated C++ bindings. We'll show how these " +"are setup on the next slide." +msgstr "" +"指出 `libcxx_test_bridge_header 和 `libcxx_test_bridge_code` 是 CXX 產生的 C+" +"+ 繫結依附元件。下一張投影片將說明相關設定方法。" + +#: src/android/interoperability/cpp/android-build-cpp.md +msgid "" +"Note that you also need to depend on the `cxx-bridge-header` library in " +"order to pull in common CXX definitions." +msgstr "" +"請注意,您也需要依賴 `cxx-bridge-header` 程式庫,才能提取常見的 CXX 定義。" + +#: src/android/interoperability/cpp/android-build-cpp.md +msgid "" +"Full docs for using CXX in Android can be found in [the Android docs]" +"(https://source.android.com/docs/setup/build/rust/building-rust-modules/" +"android-rust-patterns#rust-cpp-interop-using-cxx). You may want to share " +"that link with the class so that students know where they can find these " +"instructions again in the future." +msgstr "" +"如需介紹如何在 Android 中使用 CXX 的完整文件,請參閱 [Android 說明文件]" +"(https://source.android.com/docs/setup/build/rust/building-rust-modules/" +"android-rust-patterns#rust-cpp-interop-using-cxx)。您可以與全班分享該連結,這" +"樣學生就知道以後能在哪裡找到這些說明。" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "" +"Create two genrules: One to generate the CXX header, and one to generate the " +"CXX source file. These are then used as inputs to the `cc_library_static`." +msgstr "" +"建立兩項 genrule,分別用來產生 CXX 標頭和 CXX 來源檔案。這些項目之後會用做 " +"`cc_library_static` 的輸入內容。" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "" +"// Generate a C++ header containing the C++ bindings\n" +"// to the Rust exported functions in lib.rs.\n" +msgstr "" +"// Generate a C++ header containing the C++ bindings\n" +"// to the Rust exported functions in lib.rs.\n" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"cxxbridge\"" +msgstr "\"cxxbridge\"" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"$(location cxxbridge) $(in) --header > $(out)\"" +msgstr "\"$(location cxxbridge) $(in) --header > $(out)\"" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +#: src/android/interoperability/cpp/android-build-rust.md +msgid "\"lib.rs\"" +msgstr "\"lib.rs\"" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"lib.rs.h\"" +msgstr "\"lib.rs.h\"" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "// Generate the C++ code that Rust calls into.\n" +msgstr "// Generate the C++ code that Rust calls into.\n" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"$(location cxxbridge) $(in) > $(out)\"" +msgstr "\"$(location cxxbridge) $(in) > $(out)\"" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "\"lib.rs.cc\"" +msgstr "\"lib.rs.cc\"" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "" +"The `cxxbridge` tool is a standalone tool that generates the C++ side of the " +"bridge module. It is included in Android and available as a Soong tool." +msgstr "" +"`cxxbridge` 是用來產生 C++ 端橋接模組的獨立工具,屬於 Android 的一部分,並以 " +"Soong 工具的形式提供。" + +#: src/android/interoperability/cpp/android-cpp-genrules.md +msgid "" +"By convention, if your Rust source file is `lib.rs` your header file will be " +"named `lib.rs.h` and your source file will be named `lib.rs.cc`. This naming " +"convention isn't enforced, though." +msgstr "" +"按照慣例,如果 Rust 來源檔案是 `lib.rs`,標頭檔案會命名為 `lib.rs.h`,來源檔" +"案的名稱則是 `lib.rs.cc`。不過,系統不會強制執行這項命名慣例。" + +#: src/android/interoperability/cpp/android-build-rust.md +msgid "" +"Create a `rust_binary` that depends on `libcxx` and your `cc_library_static`." +msgstr "建立依附於 `libcxx` 和 `cc_library_static` 的 rust_binary`。" + +#: src/android/interoperability/cpp/android-build-rust.md +msgid "\"cxx_test\"" +msgstr "\"cxx_test\"" + +#: src/android/interoperability/cpp/android-build-rust.md +msgid "\"libcxx\"" +msgstr "\"libcxx\"" + +#: src/android/interoperability/java.md msgid "Interoperability with Java" -msgstr "" +msgstr "與 Java 的互通性" -#: src/android/interoperability/java.md:3 +#: src/android/interoperability/java.md msgid "" "Java can load shared objects via [Java Native Interface (JNI)](https://en." "wikipedia.org/wiki/Java_Native_Interface). The [`jni` crate](https://docs.rs/" "jni/) allows you to create a compatible library." msgstr "" +"Java 可透過 [Java 原生介面 (JNI)](https://en.wikipedia.org/wiki/" +"Java_Native_Interface) 載入共用物件。[`jni` Crate](https://docs.rs/jni/) 可用" +"來建立相容的程式庫。" -#: src/android/interoperability/java.md:7 +#: src/android/interoperability/java.md msgid "First, we create a Rust function to export to Java:" -msgstr "" +msgstr "首先,要建立用來匯出至 Java 的 Rust 函式:" -#: src/android/interoperability/java.md:9 +#: src/android/interoperability/java.md msgid "_interoperability/java/src/lib.rs_:" -msgstr "" +msgstr "__interoperability/java/src/lib.rs:" -#: src/android/interoperability/java.md:11 -msgid "" -"```rust,compile_fail\n" -"//! Rust <-> Java FFI demo.\n" -"\n" -"use jni::objects::{JClass, JString};\n" -"use jni::sys::jstring;\n" -"use jni::JNIEnv;\n" -"\n" -"/// HelloWorld::hello method implementation.\n" -"#[no_mangle]\n" -"pub extern \"system\" fn Java_HelloWorld_hello(\n" -" env: JNIEnv,\n" -" _class: JClass,\n" -" name: JString,\n" -") -> jstring {\n" -" let input: String = env.get_string(name).unwrap().into();\n" -" let greeting = format!(\"Hello, {input}!\");\n" -" let output = env.new_string(greeting).unwrap();\n" -" output.into_inner()\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/java.md +msgid "//! Rust <-> Java FFI demo.\n" +msgstr "//! Rust <-> Java FFI demo.\n" -#: src/android/interoperability/java.md:32 -#: src/android/interoperability/java.md:62 +#: src/android/interoperability/java.md +msgid "/// HelloWorld::hello method implementation.\n" +msgstr "/// HelloWorld::hello method implementation.\n" + +#: src/android/interoperability/java.md +msgid "\"system\"" +msgstr "\"system\"" + +#: src/android/interoperability/java.md +msgid "\"Hello, {input}!\"" +msgstr "\"Hello, {input}!\"" + +#: src/android/interoperability/java.md msgid "_interoperability/java/Android.bp_:" -msgstr "" +msgstr "__interoperability/java/Android.bp:" -#: src/android/interoperability/java.md:34 -msgid "" -"```javascript\n" -"rust_ffi_shared {\n" -" name: \"libhello_jni\",\n" -" crate_name: \"hello_jni\",\n" -" srcs: [\"src/lib.rs\"],\n" -" rustlibs: [\"libjni\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/java.md +msgid "\"libhello_jni\"" +msgstr "\"libhello_jni\"" -#: src/android/interoperability/java.md:43 -msgid "Finally, we can call this function from Java:" -msgstr "" +#: src/android/interoperability/java.md +msgid "\"hello_jni\"" +msgstr "\"hello_jni\"" -#: src/android/interoperability/java.md:45 +#: src/android/interoperability/java.md +msgid "\"libjni\"" +msgstr "\"libjni\"" + +#: src/android/interoperability/java.md +msgid "We then call this function from Java:" +msgstr "接著,我們會從 Java 呼叫這個函式:" + +#: src/android/interoperability/java.md msgid "_interoperability/java/HelloWorld.java_:" -msgstr "" +msgstr "__interoperability/java/HelloWorld.java:" -#: src/android/interoperability/java.md:47 -msgid "" -"```java\n" -"class HelloWorld {\n" -" private static native String hello(String name);\n" -"\n" -" static {\n" -" System.loadLibrary(\"hello_jni\");\n" -" }\n" -"\n" -" public static void main(String[] args) {\n" -" String output = HelloWorld.hello(\"Alice\");\n" -" System.out.println(output);\n" -" }\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/java.md +msgid "\"helloworld_jni\"" +msgstr "\"helloworld_jni\"" -#: src/android/interoperability/java.md:64 -msgid "" -"```javascript\n" -"java_binary {\n" -" name: \"helloworld_jni\",\n" -" srcs: [\"HelloWorld.java\"],\n" -" main_class: \"HelloWorld\",\n" -" required: [\"libhello_jni\"],\n" -"}\n" -"```" -msgstr "" +#: src/android/interoperability/java.md +msgid "\"HelloWorld.java\"" +msgstr "\"HelloWorld.java\"" -#: src/android/interoperability/java.md:73 +#: src/android/interoperability/java.md +msgid "\"HelloWorld\"" +msgstr "\"HelloWorld\"" + +#: src/android/interoperability/java.md msgid "Finally, you can build, sync, and run the binary:" -msgstr "" +msgstr "最後,您可以建構、同步處理及執行二進位檔:" -#: src/android/interoperability/java.md:75 -msgid "" -"```shell\n" -"$ m helloworld_jni\n" -"$ adb sync # requires adb root && adb remount\n" -"$ adb shell /system/bin/helloworld_jni\n" -"```" -msgstr "" - -#: src/exercises/android/morning.md:3 +#: src/exercises/android/morning.md msgid "" "This is a group exercise: We will look at one of the projects you work with " "and try to integrate some Rust into it. Some suggestions:" msgstr "" +"這是小組練習:我們會查看您的其中一項專案,嘗試將一些 Rust 整合至該專案。建議" +"事項:" -#: src/exercises/android/morning.md:6 +#: src/exercises/android/morning.md msgid "Call your AIDL service with a client written in Rust." -msgstr "" +msgstr "使用以 Rust 編寫的用戶端呼叫 AIDL 服務。" -#: src/exercises/android/morning.md:8 +#: src/exercises/android/morning.md msgid "Move a function from your project to Rust and call it." -msgstr "" +msgstr "將函式從專案移至 Rust,並呼叫該函式。" -#: src/exercises/android/morning.md:12 +#: src/exercises/android/morning.md msgid "" "No solution is provided here since this is open-ended: it relies on someone " "in the class having a piece of code which you can turn in to Rust on the fly." msgstr "" +"這裡未提供解決方案,因為這是開放式練習:您需要使用班上同學的程式碼當場轉換為 " +"Rust。" -#: src/bare-metal.md:1 -msgid "Welcome to Bare Metal Rust" +#: src/chromium.md +msgid "Welcome to Rust in Chromium" +msgstr "歡迎瞭解 Chromium 中的 Rust" + +#: src/chromium.md +msgid "" +"Rust is supported for third-party libraries in Chromium, with first-party " +"glue code to connect between Rust and existing Chromium C++ code." msgstr "" +"Chromium 中的第三方程式庫支援 Rust,且有第一方黏合程式碼可連結 Rust 和現有的 " +"Chromium C++ 程式碼。" -#: src/bare-metal.md:3 +#: src/chromium.md +msgid "" +"Today, we'll call into Rust to do something silly with strings. If you've " +"got a corner of the code where you're displaying a UTF8 string to the user, " +"feel free to follow this recipe in your part of the codebase instead of the " +"exact part we talk about." +msgstr "" +"今天我們會在 Rust 中用字串做些小事。如果您有一小部份的程式碼要向使用者顯示 " +"UTF8 字串,您可以在自己的程式碼集內採用這個方案,不必採用我們所介紹的該部分程" +"式碼集。" + +#: src/chromium/setup.md +msgid "" +"Make sure you can build and run Chromium. Any platform and set of build " +"flags is OK, so long as your code is relatively recent (commit position " +"1223636 onwards, corresponding to November 2023):" +msgstr "" +"請確認您可以建構並執行 Chromium。任何平台和建構標記組合都可以,只要程式碼相對" +"較新即可 (提交位置在 1223636 之後,日期對應到 2023 年 11 月):" + +#: src/chromium/setup.md +msgid "" +"(A component, debug build is recommended for quickest iteration time. This " +"is the default!)" +msgstr "(如要達到最快的疊代速度,建議使用元件式及偵錯版本。這是預設情形!)" + +#: src/chromium/setup.md +msgid "" +"See [How to build Chromium](https://www.chromium.org/developers/how-tos/get-" +"the-code/) if you aren't already at that point. Be warned: setting up to " +"build Chromium takes time." +msgstr "" +"如果尚未這麼做,請查看[建構 Chromium 的方法](https://www.chromium.org/" +"developers/how-tos/get-the-code/)。提醒您,設定 Chromium 建構作業需要一段時" +"間。" + +#: src/chromium/setup.md +msgid "It's also recommended that you have Visual Studio code installed." +msgstr "此外,也建議您安裝 Visual Studio Code。" + +#: src/chromium/setup.md +msgid "About the exercises" +msgstr "關於練習" + +#: src/chromium/setup.md +msgid "" +"This part of the course has a series of exercises which build on each other. " +"We'll be doing them spread throughout the course instead of just at the end. " +"If you don't have time to complete a certain part, don't worry: you can " +"catch up in the next slot." +msgstr "" +"這部分的課程包含一系列連貫的練習。我們會在課程中穿插練習,而不是放到最後。如" +"果沒時間完成某個部分也不必擔心,下次補上即可。" + +#: src/chromium/cargo.md +msgid "" +"The Rust community typically uses `cargo` and libraries from [crates.io]" +"(https://crates.io/). Chromium is built using `gn` and `ninja` and a curated " +"set of dependencies." +msgstr "" +"Rust 社群一般使用 `cargo` 和 [crates.io](https://crates.io/) 的程式庫。" +"Chromium 是以 `gn` 和 `ninja` 技術和一組精選的依附元件建構而成。" + +#: src/chromium/cargo.md +msgid "When writing code in Rust, your choices are:" +msgstr "在 Rust 中編寫程式碼時,您有以下選擇:" + +#: src/chromium/cargo.md +msgid "" +"Use `gn` and `ninja` with the help of the templates from `//build/rust/*." +"gni` (e.g. `rust_static_library` that we'll meet later). This uses " +"Chromium's audited toolchain and crates." +msgstr "" +"藉助 `//build/rust/*.gni` 中的範本 (例如 `rust_static_library`,稍後會介紹)," +"使用 `gn` 和 `ninja`。這麼做會使用 Chromium 經稽核的工具鏈和 Crate。" + +#: src/chromium/cargo.md +msgid "" +"Use `cargo`, but [restrict yourself to Chromium's audited toolchain and " +"crates](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/" +"docs/rust.md#Using-cargo)" +msgstr "" +"使用 `cargo`,但[限制自己使用 Chromium 經稽核的工具鏈和 Crate](https://" +"chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/rust.md#Using-" +"cargo)" + +#: src/chromium/cargo.md +msgid "" +"Use `cargo`, trusting a [toolchain](https://rustup.rs/) and/or [crates " +"downloaded from the internet](https://crates.io/)" +msgstr "" +"使用 `cargo`,信任[工具鏈](https://rustup.rs/)和/或[從網際網路下載的 Crate]" +"(https://crates.io/)" + +#: src/chromium/cargo.md +msgid "" +"From here on we'll be focusing on `gn` and `ninja`, because this is how Rust " +"code can be built into the Chromium browser. At the same time, Cargo is an " +"important part of the Rust ecosystem and you should keep it in your toolbox." +msgstr "" +"接下來的重點將放在 `gn` 和 `ninja`,因為這就是將 Rust 程式碼建構至 Chromium " +"瀏覽器中的方式。同時,Cargo 是 Rust 生態系統中重要的一環,因此您應該學會使用" +"這項工具。" + +#: src/chromium/cargo.md +#, fuzzy +msgid "Mini exercise" +msgstr "練習" + +#: src/chromium/cargo.md +msgid "Split into small groups and:" +msgstr "請分成小組,按照下列指示開始練習:" + +#: src/chromium/cargo.md +msgid "" +"Brainstorm scenarios where `cargo` may offer an advantage and assess the " +"risk profile of these scenarios." +msgstr "發想各種 `cargo` 可帶來優勢的情境,然後評估這些情境的風險狀況。" + +#: src/chromium/cargo.md +msgid "" +"Discuss which tools, libraries, and groups of people need to be trusted when " +"using `gn` and `ninja`, offline `cargo`, etc." +msgstr "" +"討論使用 `gn` 和 `ninja`、離線 `cargo` 等技術時,需要信任哪些工具、程式庫和人" +"員。" + +#: src/chromium/cargo.md +msgid "" +"Ask students to avoid peeking at the speaker notes before completing the " +"exercise. Assuming folks taking the course are physically together, ask them " +"to discuss in small groups of 3-4 people." +msgstr "" +"請要求學生不要在完成練習前偷看演講者備忘稿。如果學生在彼此身邊,請要求他們分" +"為 3 到 4 人一組一起討論。" + +#: src/chromium/cargo.md +msgid "" +"Notes/hints related to the first part of the exercise (\"scenarios where " +"Cargo may offer an advantage\"):" +msgstr "與第一部分練習 (「Cargo 可帶來優勢的情境」) 相關的附註/提示:" + +#: src/chromium/cargo.md +msgid "" +"It's fantastic that when writing a tool, or prototyping a part of Chromium, " +"one has access to the rich ecosystem of crates.io libraries. There is a " +"crate for almost anything and they are usually quite pleasant to use. " +"(`clap` for command-line parsing, `serde` for serializing/deserializing to/" +"from various formats, `itertools` for working with iterators, etc.)." +msgstr "" +"很棒的是,在編寫工具或設計 Chromium 中某部分的原型時,開發人員可以存取 " +"crates.io 程式庫豐富的生態系統。幾乎所有東西都有 Crate,而且使用方法通常很簡" +"便 (用於指令列剖析的 `clap`、用於將各種格式序列化/反序列化的 `serde`,以及與" +"疊代器搭配使用的 `itertools` 等)。" + +#: src/chromium/cargo.md +msgid "" +"`cargo` makes it easy to try a library (just add a single line to `Cargo." +"toml` and start writing code)" +msgstr "" +"您可以透過 `cargo` 輕鬆試用程式庫 (在 `Cargo.toml` 中新增一行程式碼,然後開始" +"編寫程式碼即可)" + +#: src/chromium/cargo.md +msgid "" +"It may be worth comparing how CPAN helped make `perl` a popular choice. Or " +"comparing with `python` + `pip`." +msgstr "" +"可考慮比較 CPAN 如何讓 `perl` 成為熱門選擇,或是與 `python` + `pip` 比較。" + +#: src/chromium/cargo.md +msgid "" +"Development experience is made really nice not only by core Rust tools (e.g. " +"using `rustup` to switch to a different `rustc` version when testing a crate " +"that needs to work on nightly, current stable, and older stable) but also by " +"an ecosystem of third-party tools (e.g. Mozilla provides `cargo vet` for " +"streamlining and sharing security audits; `criterion` crate gives a " +"streamlined way to run benchmarks)." +msgstr "" +"之所以能實現優異的開發體驗,一來是因為有核心 Rust 工具,例如想測試的 Crate 需" +"在每夜版、目前穩定版和較舊穩定版執行時,可使用 `rustup` 切換至其他 `rustc` 版" +"本。二來是因為有第三方工具的生態系統,例如 Mozilla 提供的 `cargo vet` 可簡化" +"及分享安全性稽核作業,`criterion` Crate 則能簡化執行基準測試的方式。" + +#: src/chromium/cargo.md +msgid "" +"`cargo` makes it easy to add a tool via `cargo install --locked cargo-vet`." +msgstr "" +"有了 `cargo`,您可以輕鬆透過 `cargo install --locked cargo-vet` 新增工具。" + +#: src/chromium/cargo.md +msgid "It may be worth comparing with Chrome Extensions or VScode extensions." +msgstr "可考慮與 Chrome 擴充功能或 VScode 擴充功能比較。" + +#: src/chromium/cargo.md +msgid "" +"Broad, generic examples of projects where `cargo` may be the right choice:" +msgstr "以下列出廣泛通用的專案範例,皆可能適合使用 `cargo`:" + +#: src/chromium/cargo.md +msgid "" +"Perhaps surprisingly, Rust is becoming increasingly popular in the industry " +"for writing command line tools. The breadth and ergonomics of libraries is " +"comparable to Python, while being more robust (thanks to the rich " +"typesystem) and running faster (as a compiled, rather than interpreted " +"language)." +msgstr "" +"或許令人意外的是,業界越來越廣泛使用 Rust 編寫指令列工具。Rust 程式庫在廣度和" +"人因工程學方面與 Python 不相上下,又因為豐富的型別系統而更強健,就以編譯語言 " +"(而非解譯語言) 來說,執行速度也更快。" + +#: src/chromium/cargo.md +msgid "" +"Participating in the Rust ecosystem requires using standard Rust tools like " +"Cargo. Libraries that want to get external contributions, and want to be " +"used outside of Chromium (e.g. in Bazel or Android/Soong build environments) " +"should probably use Cargo." +msgstr "" +"如要參與 Rust 生態系統,必須使用 Cargo 等標準 Rust 工具。如果程式庫要取得外部" +"貢獻,並用於 Chromium 以外的地方 (例如 Bazel 或 Android/Soong 建構環境),則大" +"概應使用 Cargo。" + +#: src/chromium/cargo.md +msgid "Examples of Chromium-related projects that are `cargo`\\-based:" +msgstr "`cargo`\\ 式的 Chromium 相關專案範例:" + +#: src/chromium/cargo.md +msgid "" +"`serde_json_lenient` (experimented with in other parts of Google which " +"resulted in PRs with performance improvements)" +msgstr "" +"`serde_json_lenient` (在 Google 的其他部分中經過實驗,產生了一些可提升效能的 " +"PR (Pull Request))" + +#: src/chromium/cargo.md +msgid "Fontations libraries like `font-types`" +msgstr "`font-types` 等字型程式庫" + +#: src/chromium/cargo.md +msgid "" +"`gnrt` tool (we will meet it later in the course) which depends on `clap` " +"for command-line parsing and on `toml` for configuration files." +msgstr "" +"`gnrt` 工具 (課程稍後會介紹),這個工具需使用 `clap` 執行指令列剖析,並需使用 " +"`toml` 處理設定檔。" + +#: src/chromium/cargo.md +msgid "" +"Disclaimer: a unique reason for using `cargo` was unavailability of `gn` " +"when building and bootstrapping Rust standard library when building Rust " +"toolchain." +msgstr "" +"免責事項:使用 `cargo` 的特別理由之一,是因為建構 Rust 工具鏈時,系統無法在建" +"構和啟動 Rust 標準程式庫期間使用 `gn`。" + +#: src/chromium/cargo.md +msgid "" +"`run_gnrt.py` uses Chromium's copy of `cargo` and `rustc`. `gnrt` depends on " +"third-party libraries downloaded from the internet, but `run_gnrt.py` asks " +"`cargo` that only `--locked` content is allowed via `Cargo.lock`.)" +msgstr "" +"`run_gnrt.py` 使用 Chromium 的 `cargo` 和 `rustc` 副本。`gnrt` 依附於從網際網" +"路下載的第三方程式庫,但 `run_gnrt.py` 透過 `Cargo.lock` 要求 `cargo` 只允許 " +"`--locked` 內容。" + +#: src/chromium/cargo.md +msgid "" +"Students may identify the following items as being implicitly or explicitly " +"trusted:" +msgstr "學生可能會認為下列項目隱含或明確受信任:" + +#: src/chromium/cargo.md +msgid "" +"`rustc` (the Rust compiler) which in turn depends on the LLVM libraries, the " +"Clang compiler, the `rustc` sources (fetched from GitHub, reviewed by Rust " +"compiler team), binary Rust compiler downloaded for bootstrapping" +msgstr "" +"`rustc` (Rust 編譯器) 依序依附於 LLVM 程式庫、Clang 編譯器、`rustc` 原始碼 " +"(從 GitHub 擷取,由 Rust 編譯器團隊審查)、為自舉而下載的二進位檔 Rust 編譯器" + +#: src/chromium/cargo.md +msgid "" +"`rustup` (it may be worth pointing out that `rustup` is developed under the " +"umbrella of the https://github.com/rust-lang/ organization - same as `rustc`)" +msgstr "" +"`rustup` (可考慮告知學生 `rustup` 是 https://github.com/rust-lang/ 組織所開發" +"的一系列項目之一,與 `rustc` 相同)" + +#: src/chromium/cargo.md +msgid "`cargo`, `rustfmt`, etc." +msgstr "`cargo`、`rustfmt` 等" + +#: src/chromium/cargo.md +msgid "" +"Various internal infrastructure (bots that build `rustc`, system for " +"distributing the prebuilt toolchain to Chromium engineers, etc.)" +msgstr "" +"各種內部基礎架構 (建構 `rustc` 的機器人、將預建工具鏈發布給 Chromium 工程師的" +"系統等)" + +#: src/chromium/cargo.md +msgid "Cargo tools like `cargo audit`, `cargo vet`, etc." +msgstr "Cargo 工具,例如 `cargo audit`、`cargo vet` 等" + +#: src/chromium/cargo.md +msgid "" +"Rust libraries vendored into `//third_party/rust` (audited by " +"security@chromium.org)" +msgstr "" +"供應至 `//third_party/rust` 的 Rust 程式庫 (由 security@chromium.org 稽核)" + +#: src/chromium/cargo.md +msgid "Other Rust libraries (some niche, some quite popular and commonly used)" +msgstr "其他 Rust 程式庫 (有些很小眾,有些相當受歡迎也常用)" + +#: src/chromium/policy.md +msgid "Chromium Rust policy" +msgstr "Chromium Rust 政策" + +#: src/chromium/policy.md +msgid "" +"Chromium does not yet allow first-party Rust except in rare cases as " +"approved by Chromium's [Area Tech Leads](https://source.chromium.org/" +"chromium/chromium/src/+/main:ATL_OWNERS)." +msgstr "" +"Chromium 目前不支援第一方 Rust,除非是 Chromium [領域技術主管](https://" +"source.chromium.org/chromium/chromium/src/+/main:ATL_OWNERS)核准的少數情況。" + +#: src/chromium/policy.md +msgid "" +"Chromium's policy on third party libraries is outlined [here](https://" +"chromium.googlesource.com/chromium/src/+/main/docs/adding_to_third_party." +"md#rust) - Rust is allowed for third party libraries under various " +"circumstances, including if they're the best option for performance or for " +"security." +msgstr "" +"Chromium 的第三方程式庫政策列載於[這個頁面](https://chromium.googlesource." +"com/chromium/src/+/main/docs/adding_to_third_party.md#rust) - 第三方程式庫可" +"在各種情況下使用 Rust,包括這些程式庫是效能或安全方面的最佳選擇時。" + +#: src/chromium/policy.md +msgid "" +"Very few Rust libraries directly expose a C/C++ API, so that means that " +"nearly all such libraries will require a small amount of first-party glue " +"code." +msgstr "" +"只有極少數的 Rust 程式庫會直接公開 C/C++ API,這表示幾乎所有這類程式庫都需要" +"少量的第一方黏合程式碼。" + +#: src/chromium/policy.md +#, fuzzy +msgid "" +"```bob\n" +"\"C++\" Rust\n" +".- - - - - - - - - -. .- - - - - - - - - - - - - - - - - - - - - - " +"-.\n" +": : : :\n" +": Existing Chromium : : Chromium Rust Existing " +"Rust :\n" +": \"C++\" : : \"wrapper\" " +"crate :\n" +": +---------------+ : : +----------------+ +-------------" +"+ :\n" +": | | : : | | | " +"| :\n" +": | o-----+-+-----------+-+-> o-+----------+--> " +"| :\n" +": | | : Language : | | Crate | " +"| :\n" +": +---------------+ : boundary : +----------------+ API +-------------" +"+ :\n" +": : : :\n" +"`- - - - - - - - - -' `- - - - - - - - - - - - - - - - - - - - - - " +"-'\n" +"```" +msgstr "" +"```bob\n" +" 堆疊 堆積\n" +".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - - - -.\n" +": : : :\n" +": s1 : : :\n" +": +-----------+-------+ : : +----+----+----+----+----+ :\n" +": | ptr | o---+---+-----+-->| H | e | l | l | o | :\n" +": | len | 5 | : : +----+----+----+----+----+ :\n" +": | capacity | 5 | : : :\n" +": +-----------+-------+ : : :\n" +": : `- - - - - - - - - - - - - - - -'\n" +"`- - - - - - - - - - - - - -'\n" +"```" + +#: src/chromium/policy.md +msgid "" +"First-party Rust glue code for a particular third-party crate should " +"normally be kept in `third_party/rust///wrapper`." +msgstr "" +"特定第三方 Crate 的第一方 Rust 黏合程式碼通常應儲存在 `third_party/rust/" +"//wrapper`。" + +#: src/chromium/policy.md +msgid "Because of this, today's course will be heavily focused on:" +msgstr "因此,今天的課程會著重在以下層面:" + +#: src/chromium/policy.md +msgid "Bringing in third-party Rust libraries (\"crates\")" +msgstr "導入第三方 Rust 程式庫 (「Crates」)" + +#: src/chromium/policy.md +msgid "Writing glue code to be able to use those crates from Chromium C++." +msgstr "編寫黏合程式碼,以使用 Chromium C++ 中的 Crate。" + +#: src/chromium/policy.md +msgid "If this policy changes over time, the course will evolve to keep up." +msgstr "如果本政策有所異動,課程內容也會隨之更新。" + +#: src/chromium/build-rules.md +#, fuzzy +msgid "Build rules" +msgstr "建構規則" + +#: src/chromium/build-rules.md +msgid "" +"Rust code is usually built using `cargo`. Chromium builds with `gn` and " +"`ninja` for efficiency --- its static rules allow maximum parallelism. Rust " +"is no exception." +msgstr "" +"Rust 程式碼通常是以 `cargo` 建構。為提升建構效率,Chromium 會使用 `gn` 和 " +"`ninja`,因為 Chromium 的靜態規則允許最大程度的平行處理。Rust 也不例外。" + +#: src/chromium/build-rules.md +msgid "Adding Rust code to Chromium" +msgstr "將 Rust 程式碼新增至 Chromium" + +#: src/chromium/build-rules.md +msgid "" +"In some existing Chromium `BUILD.gn` file, declare a `rust_static_library`:" +msgstr "在某個現有的 Chromium `BUILD.gn` 檔案中,宣告 `rust_static_library`:" + +#: src/chromium/build-rules.md +msgid "" +"```gn\n" +"import(\"//build/rust/rust_static_library.gni\")\n" +"\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [ \"lib.rs\" ]\n" +"}\n" +"```" +msgstr "" +"```gn\n" +"import(\"//build/rust/rust_static_library.gni\")\n" +"\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [ \"lib.rs\" ]\n" +"}\n" +"```" + +#: src/chromium/build-rules.md +msgid "" +"You can also add `deps` on other Rust targets. Later we'll use this to " +"depend upon third party code." +msgstr "" +"您也可以在其他 Rust 目標中新增 `deps`。稍後我們會使用此程式碼,依附於第三方程" +"式碼。" + +#: src/chromium/build-rules.md +msgid "" +"You must specify _both_ the crate root, _and_ a full list of sources. The " +"`crate_root` is the file given to the Rust compiler representing the root " +"file of the compilation unit --- typically `lib.rs`. `sources` is a complete " +"list of all source files which `ninja` needs in order to determine when " +"rebuilds are necessary." +msgstr "" +"您必須「同時」指定 Crate 根層級「以及」完整的來源清單。`crate_root` 是提供給 " +"Rust 編譯器的檔案,代表編譯單元的根檔案 (通常是 `lib.rs`)。`sources` 是列出所" +"有來源檔案的完整清單,`ninja` 判斷何時必須重建時,就需要使用此清單。" + +#: src/chromium/build-rules.md +msgid "" +"(There's no such thing as a Rust `source_set`, because in Rust, an entire " +"crate is a compilation unit. A `static_library` is the smallest unit.)" +msgstr "" +"(並不存在 Rust 的 `source_set` 這種東西,因為在 Rust 中,整個 Crate 就是編譯" +"單元。`static_library` 是最小單元。)" + +#: src/chromium/build-rules.md +msgid "" +"Students might be wondering why we need a gn template, rather than using " +"[gn's built-in support for Rust static libraries](https://gn.googlesource." +"com/gn/+/main/docs/reference.md#func_static_library). The answer is that " +"this template provides support for CXX interop, Rust features, and unit " +"tests, some of which we'll use later." +msgstr "" +"學生可能會想知道為何需要 gn 範本,而不是使用 [gn 內建的 Rust 靜態程式庫支援功" +"能](https://gn.googlesource.com/gn/+/main/docs/reference." +"md#func_static_library)。答案是這個範本可支援 CXX 互通性、Rust 功能和單元測" +"試,其中一些項目稍後會用到。" + +#: src/chromium/build-rules/unsafe.md +msgid "Including `unsafe` Rust Code" +msgstr "包含 `unsafe` Rust 程式碼" + +#: src/chromium/build-rules/unsafe.md +msgid "" +"Unsafe Rust code is forbidden in `rust_static_library` by default --- it " +"won't compile. If you need unsafe Rust code, add `allow_unsafe = true` to " +"the gn target. (Later in the course we'll see circumstances where this is " +"necessary.)" +msgstr "" +"根據預設,`rust_static_library` 中禁止使用不安全的 Rust 程式碼,系統也不會編" +"譯這類程式碼。如果需要不安全的 Rust 程式碼,請在 gn 目標中加入 `allow_unsafe " +"= true` (本課程稍後會說明必須這麼做的情況)。" + +#: src/chromium/build-rules/unsafe.md +msgid "" +"```gn\n" +"import(\"//build/rust/rust_static_library.gni\")\n" +"\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [\n" +" \"lib.rs\",\n" +" \"hippopotamus.rs\"\n" +" ]\n" +" allow_unsafe = true\n" +"}\n" +"```" +msgstr "" +"```gn\n" +"import(\"//build/rust/rust_static_library.gni\")\n" +"\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [\n" +" \"lib.rs\",\n" +" \"hippopotamus.rs\"\n" +" ]\n" +" allow_unsafe = true\n" +"}\n" +"```" + +#: src/chromium/build-rules/depending.md +msgid "Simply add the above target to the `deps` of some Chromium C++ target." +msgstr "將上述目標新增至某個 Chromium C++ 目標的 `deps` 即可。" + +#: src/chromium/build-rules/depending.md +msgid "" +"```gn\n" +"import(\"//build/rust/rust_static_library.gni\")\n" +"\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [ \"lib.rs\" ]\n" +"}\n" +"\n" +"# or source_set, static_library etc.\n" +"component(\"preexisting_cpp\") {\n" +" deps = [ \":my_rust_lib\" ]\n" +"}\n" +"```" +msgstr "" +"```gn\n" +"import(\"//build/rust/rust_static_library.gni\")\n" +"\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [ \"lib.rs\" ]\n" +"}\n" +"\n" +"# 或 source_set, static_library 等等。\n" +"component(\"preexisting_cpp\") {\n" +" deps = [ \":my_rust_lib\" ]\n" +"}\n" +"```" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Types are elided in Rust code, which makes a good IDE even more useful than " +"for C++. Visual Studio code works well for Rust in Chromium. To use it," +msgstr "" +"Rust 程式碼中省略了型別,因此相較於 C++ 而言,使用優質的 IDE 會更加有效。" +"Visual Studio Code 很適合 Chromium 中的 Rust。使用方法:" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Ensure your VSCode has the `rust-analyzer` extension, not earlier forms of " +"Rust support" +msgstr "確認 VSCode 具有 `rust-analyzer` 擴充功能,而非舊版 Rust 支援功能" + +#: src/chromium/build-rules/vscode.md +msgid "" +"`gn gen out/Debug --export-rust-project` (or equivalent for your output " +"directory)" +msgstr "`gn gen out/Debug --export-rust-project` (或換成您的輸出目錄)" + +#: src/chromium/build-rules/vscode.md +msgid "`ln -s out/Debug/rust-project.json rust-project.json`" +msgstr "`ln -s out/Debug/rust-project.json rust-project.json`" + +#: src/chromium/build-rules/vscode.md +msgid "" +"A demo of some of the code annotation and exploration features of rust-" +"analyzer might be beneficial if the audience are naturally skeptical of IDEs." +msgstr "" +"如果大家對 IDE 自然產生懷疑,示範 rust-analyzer 的一些程式碼註解和探索功能或" +"許會有幫助。" + +#: src/chromium/build-rules/vscode.md +msgid "" +"The following steps may help with the demo (but feel free to instead use a " +"piece of Chromium-related Rust that you are most familiar with):" +msgstr "" +"下列步驟或許有助於示範 (不過您可以改用自己最熟悉的 Chromium 相關 Rust 程式" +"碼):" + +#: src/chromium/build-rules/vscode.md +msgid "Open `components/qr_code_generator/qr_code_generator_ffi_glue.rs`" +msgstr "開啟 `components/qr_code_generator/qr_code_generator_ffi_glue.rs`" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Place the cursor over the `QrCode::new` call (around line 26) in " +"\\`qr_code_generator_ffi_glue.rs" +msgstr "" +"將游標移到 \\`qr_code_generator_ffi_glue.rs 中的 `QrCode::new` 呼叫 (約在第 " +"26 行)。" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Demo **show documentation** (typical bindings: vscode = ctrl k i; vim/CoC = " +"K)." +msgstr "示範「顯示說明文件」(一般繫結:vscode = ctrl k i; vim/CoC = K)。" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Demo **go to definition** (typical bindings: vscode = F12; vim/CoC = g d). " +"(This will take you to `//third_party/rust/.../qr_code-.../src/lib.rs`.)" +msgstr "" +"示範「前往定義」(一般繫結:vscode = F12; vim/CoC = g d)。(您將前往 `//" +"third_party/rust/.../qr_code-.../src/lib.rs`)。" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Demo **outline** and navigate to the `QrCode::with_bits` method (around line " +"164; the outline is in the file explorer pane in vscode; typical vim/CoC " +"bindings = space o)" +msgstr "" +"示範「大綱」,並前往 `QrCode::with_bits` 方法 (約在 164 行;大綱位於 vscode " +"的檔案總管窗格;一般 vim/CoC 繫結 = 空格 o)" + +#: src/chromium/build-rules/vscode.md +msgid "" +"Demo **type annotations** (there are quote a few nice examples in the " +"`QrCode::with_bits` method)" +msgstr "示範「型別註解」(`QrCode::with_bits` 方法中引用了幾個不錯的範例)" + +#: src/chromium/build-rules/vscode.md +msgid "" +"It may be worth pointing out that `gn gen ... --export-rust-project` will " +"need to be rerun after editing `BUILD.gn` files (which we will do a few " +"times throughout the exercises in this session)." +msgstr "" +"可考慮指出在編輯 `BUILD.gn` 檔案之後,需要重新執行 `gn gen ... --export-rust-" +"project` (我們會在本課程的練習中多次執行此操作)。" + +#: src/exercises/chromium/build-rules.md +#, fuzzy +msgid "Build rules exercise" +msgstr "建構規則練習" + +#: src/exercises/chromium/build-rules.md +msgid "" +"In your Chromium build, add a new Rust target to `//ui/base/BUILD.gn` " +"containing:" +msgstr "" +"在您的 Chromium 版本中,將新的 Rust 目標加至 `//ui/base/BUILD.gn`,其中包含以" +"下內容:" + +#: src/exercises/chromium/build-rules.md +#, fuzzy +msgid "" +"**Important**: note that `no_mangle` here is considered a type of unsafety " +"by the Rust compiler, so you'll need to allow unsafe code in your `gn` " +"target." +msgstr "" +"**重要事項**:請注意,Rust 編譯器會將此處的 `no_mangle` 視為不安全型別,因此" +"您需要在 `gn` 目標中允許不安全的程式碼。" + +#: src/exercises/chromium/build-rules.md +msgid "" +"Add this new Rust target as a dependency of `//ui/base:base`. Declare this " +"function at the top of `ui/base/resource/resource_bundle.cc` (later, we'll " +"see how this can be automated by bindings generation tools):" +msgstr "" +"將這個新的 Rust 目標新增為 `//ui/base:base` 的依附元件。在 `ui/base/resource/" +"resource_bundle.cc` 頂端宣告此函式 (稍後會說明如何使用繫結產生工具自動執行此" +"操作):" + +#: src/exercises/chromium/build-rules.md +msgid "" +"Call this function from somewhere in `ui/base/resource/resource_bundle.cc` - " +"we suggest the top of `ResourceBundle::MaybeMangleLocalizedString`. Build " +"and run Chromium, and ensure that \"Hello from Rust!\" is printed lots of " +"times." +msgstr "" +"從 `ui/base/resource/resource_bundle.cc` 的某處呼叫此函式,建議位置是 " +"`ResourceBundle::MaybeMangleLocalizedString` 的頂端。建構及執行 Chromium,確" +"認系統多次顯示「Hello from Rust!」。" + +#: src/exercises/chromium/build-rules.md +msgid "" +"If you use VSCode, now set up Rust to work well in VSCode. It will be useful " +"in subsequent exercises. If you've succeeded, you will be able to use right-" +"click \"Go to definition\" on `println!`." +msgstr "" +"如果使用 VSCode,現在請設定 Rust,讓 Rust 在 VSCode 中順利運作。這在後續練習" +"中會很實用。如果您成功完成,就能在 `println!` 中以滑鼠右鍵按一下「Go to " +"definition」。" + +#: src/exercises/chromium/build-rules.md +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Where to find help" +msgstr "如何找到說明" + +#: src/exercises/chromium/build-rules.md +msgid "" +"The options available to the [`rust_static_library` gn template](https://" +"source.chromium.org/chromium/chromium/src/+/main:build/rust/" +"rust_static_library.gni;l=16)" +msgstr "" +"[`rust_static_library` gn 範本](https://source.chromium.org/chromium/" +"chromium/src/+/main:build/rust/rust_static_library.gni;l=16)提供的選項" + +#: src/exercises/chromium/build-rules.md +msgid "" +"Information about [`#[no_mangle]`](https://doc.rust-lang.org/beta/reference/" +"abi.html#the-no_mangle-attribute)" +msgstr "" +"[`#[no_mangle]`](https://doc.rust-lang.org/beta/reference/abi.html#the-" +"no_mangle-attribute) 相關資訊" + +#: src/exercises/chromium/build-rules.md +msgid "" +"Information about [`extern \"C\"`](https://doc.rust-lang.org/std/keyword." +"extern.html)" +msgstr "" +"[`extern \"C\"`](https://doc.rust-lang.org/std/keyword.extern.html) 相關資訊" + +#: src/exercises/chromium/build-rules.md +msgid "" +"Information about gn's [`--export-rust-project`](https://gn.googlesource.com/" +"gn/+/main/docs/reference.md#compilation-database) switch" +msgstr "" +"gn 的 [`--export-rust-project`](https://gn.googlesource.com/gn/+/main/docs/" +"reference.md#compilation-database) switch 相關資訊" + +#: src/exercises/chromium/build-rules.md +msgid "" +"[How to install rust-analyzer in VSCode](https://code.visualstudio.com/docs/" +"languages/rust)" +msgstr "" +"[如何在 VSCode 中安裝 rust-analyzer](https://code.visualstudio.com/docs/" +"languages/rust)" + +#: src/exercises/chromium/build-rules.md +msgid "" +"This example is unusual because it boils down to the lowest-common-" +"denominator interop language, C. Both C++ and Rust can natively declare and " +"call C ABI functions. Later in the course, we'll connect C++ directly to " +"Rust." +msgstr "" +"此範例會探究做為最小公因數的互通語言 C,因此很特別。C++ 和 Rust 都能以原生方" +"式宣告及呼叫 C ABI 函式。本課程稍後會將 C++ 直接連結至 Rust。" + +#: src/exercises/chromium/build-rules.md +msgid "" +"`allow_unsafe = true` is required here because `#[no_mangle]` might allow " +"Rust to generate two functions with the same name, and Rust can no longer " +"guarantee that the right one is called." +msgstr "" +"這裡需要 `allow_unsafe = true`,因為 `#[no_mangle]` 可能會允許 Rust 產生兩個" +"名稱相同的函式,Rust 就不再能保證系統會呼叫正確的函式。" + +#: src/exercises/chromium/build-rules.md +msgid "" +"If you need a pure Rust executable, you can also do that using the " +"`rust_executable` gn template." +msgstr "" +"如果需要純 Rust 執行檔,也可以使用 `rust_executable` gn 範本執行這項操作。" + +#: src/chromium/testing.md +msgid "" +"Rust community typically authors unit tests in a module placed in the same " +"source file as the code being tested. This was covered [earlier](../testing." +"md) in the course and looks like this:" +msgstr "" +"Rust 社群撰寫單元測試的模組,通常會位在與所測試程式碼相同的來源檔案中。這種做" +"法已在[先前課程](../testing.md)中介紹,如下所示:" + +#: src/chromium/testing.md +msgid "" +"In Chromium we place unit tests in a separate source file and we continue to " +"follow this practice for Rust --- this makes tests consistently discoverable " +"and helps to avoid rebuilding `.rs` files a second time (in the `test` " +"configuration)." +msgstr "" +"在 Chromium 中,我們將單元測試放在獨立的來源檔案中,而對 Rust 也繼續採取這項" +"做法,這樣不僅能較一致地找到測試,也有助於避免在 `test` 設定中再次重新建構 `." +"rs` 檔案。" + +#: src/chromium/testing.md +msgid "" +"This results in the following options for testing Rust code in Chromium:" +msgstr "因此 Chromium 中有以下 Rust 程式碼測試選項:" + +#: src/chromium/testing.md +msgid "" +"Native Rust tests (i.e. `#[test]`). Discouraged outside of `//third_party/" +"rust`." +msgstr "" +"原生 Rust 測試 (即 `#[test]`)。不建議在 `//third_party/rust` 之外使用。" + +#: src/chromium/testing.md +msgid "" +"`gtest` tests authored in C++ and exercising Rust via FFI calls. Sufficient " +"when Rust code is just a thin FFI layer and the existing unit tests provide " +"sufficient coverage for the feature." +msgstr "" +"在 C++ 中編寫的 `gtest` 測試,並透過 FFI 呼叫並執行 Rust。如果 Rust 程式碼只" +"是精簡的 FFI 層,這麼做就夠充分,而現有的單元測試可為這項功能提供足夠的涵蓋" +"率。" + +#: src/chromium/testing.md +msgid "" +"`gtest` tests authored in Rust and using the crate under test through its " +"public API (using `pub mod for_testing { ... }` if needed). This is the " +"subject of the next few slides." +msgstr "" +"在 Rust 中編寫的 `gtest` 測試,並透過公用 API 使用受測試的 Crate (視需要使用 " +"`pub mod for_testing { ... }`)。這是接下來幾張投影片的主題。" + +#: src/chromium/testing.md +msgid "" +"Mention that native Rust tests of third-party crates should eventually be " +"exercised by Chromium bots. (Such testing is needed rarely --- only after " +"adding or updating third-party crates.)" +msgstr "" +"請提及第三方 Crate 的原生 Rust 測試最終應由 Chromium 機器人執行 (這類測試極少" +"需要執行,只有在新增或更新第三方 Crate 後才需要)。" + +#: src/chromium/testing.md +msgid "" +"Some examples may help illustrate when C++ `gtest` vs Rust `gtest` should be " +"used:" +msgstr "以下範例或許有助說明 C++ `gtest` 和 Rust `gtest` 各自的使用時機:" + +#: src/chromium/testing.md +msgid "" +"QR has very little functionality in the first-party Rust layer (it's just a " +"thin FFI glue) and therefore uses the existing C++ unit tests for testing " +"both the C++ and the Rust implementation (parameterizing the tests so they " +"enable or disable Rust using a `ScopedFeatureList`)." +msgstr "" +"QR 在第一方 Rust 層中的功用很少 (只是精簡的 FFI 黏合工具),因此會使用現有的 " +"C++ 單元測試,測試 C++ 和 Rust 的實作項目 (將測試參數化,方便以 " +"`ScopedFeatureList` 啟用或停用 Rust)。" + +#: src/chromium/testing.md +msgid "" +"Hypothetical/WIP PNG integration may need to implement memory-safe " +"implementation of pixel transformations that are provided by `libpng` but " +"missing in the `png` crate - e.g. RGBA => BGRA, or gamma correction. Such " +"functionality may benefit from separate tests authored in Rust." +msgstr "" +"假設性/WIP PNG 整合可能需實作記憶體安全地像素轉換,這類像素轉換是由 `libpng` " +"提供,但 `png` Crate 中缺少 (例如 RGBA => BGRA 或伽馬校正)。這類功能可能受益" +"於在 Rust 中編寫的獨立測試。" + +#: src/chromium/testing/rust-gtest-interop.md +msgid "" +"The [`rust_gtest_interop`](https://chromium.googlesource.com/chromium/src/+/" +"main/testing/rust_gtest_interop/README.md) library provides a way to:" +msgstr "" +"[`rust_gtest_interop`](https://chromium.googlesource.com/chromium/src/+/main/" +"testing/rust_gtest_interop/README.md) 程式庫提供以下功能:" + +#: src/chromium/testing/rust-gtest-interop.md +msgid "" +"Use a Rust function as a `gtest` testcase (using the `#[gtest(...)]` " +"attribute)" +msgstr "使用 Rust 函式做為 `gtest` 測試案例 (使用 `#[gtest(...)]` 屬性)" + +#: src/chromium/testing/rust-gtest-interop.md +msgid "" +"Use `expect_eq!` and similar macros (similar to `assert_eq!` but not " +"panicking and not terminating the test when the assertion fails)." +msgstr "" +"使用 `expect_eq!` 和類似的巨集 (類似於 `assert_eq!`,但不會導致恐慌,斷言失敗" +"時也不會終止測試)。" + +#: src/chromium/testing/rust-gtest-interop.md +#, fuzzy +msgid "Example:" +msgstr "範例" + +#: src/chromium/testing/build-gn.md +msgid "" +"The simplest way to build Rust `gtest` tests is to add them to an existing " +"test binary that already contains tests authored in C++. For example:" +msgstr "" +"如要建構 Rust `gtest` 測試,最簡單的方法就是將這些測試新增至已包含 C++ 測試的" +"現有測試二進位檔,例如:" + +#: src/chromium/testing/build-gn.md +msgid "" +"```gn\n" +"test(\"ui_base_unittests\") {\n" +" ...\n" +" sources += [ \"my_rust_lib_unittest.rs\" ]\n" +" deps += [ \":my_rust_lib\" ]\n" +"}\n" +"```" +msgstr "" +"```gn\n" +"test(\"ui_base_unittests\") {\n" +" ...\n" +" sources += [ \"my_rust_lib_unittest.rs\" ]\n" +" deps += [ \":my_rust_lib\" ]\n" +"}\n" +"```" + +#: src/chromium/testing/build-gn.md +msgid "" +"Authoring Rust tests in a separate `static_library` also works, but requires " +"manually declaring the dependency on the support libraries:" +msgstr "" +"也可以在單獨的 `static_library` 中編寫 Rust 測試,但必須手動宣告支援程式庫的" +"依附元件:" + +#: src/chromium/testing/build-gn.md +msgid "" +"```gn\n" +"rust_static_library(\"my_rust_lib_unittests\") {\n" +" testonly = true\n" +" is_gtest_unittests = true\n" +" crate_root = \"my_rust_lib_unittest.rs\"\n" +" sources = [ \"my_rust_lib_unittest.rs\" ]\n" +" deps = [\n" +" \":my_rust_lib\",\n" +" \"//testing/rust_gtest_interop\",\n" +" ]\n" +"}\n" +"\n" +"test(\"ui_base_unittests\") {\n" +" ...\n" +" deps += [ \":my_rust_lib_unittests\" ]\n" +"}\n" +"```" +msgstr "" +"```gn\n" +"rust_static_library(\"my_rust_lib_unittests\") {\n" +" testonly = true\n" +" is_gtest_unittests = true\n" +" crate_root = \"my_rust_lib_unittest.rs\"\n" +" sources = [ \"my_rust_lib_unittest.rs\" ]\n" +" deps = [\n" +" \":my_rust_lib\",\n" +" \"//testing/rust_gtest_interop\",\n" +" ]\n" +"}\n" +"\n" +"test(\"ui_base_unittests\") {\n" +" ...\n" +" deps += [ \":my_rust_lib_unittests\" ]\n" +"}\n" +"```" + +#: src/chromium/testing/chromium-import-macro.md +msgid "" +"After adding `:my_rust_lib` to GN `deps`, we still need to learn how to " +"import and use `my_rust_lib` from `my_rust_lib_unittest.rs`. We haven't " +"provided an explicit `crate_name` for `my_rust_lib` so its crate name is " +"computed based on the full target path and name. Fortunately we can avoid " +"working with such an unwieldy name by using the `chromium::import!` macro " +"from the automatically-imported `chromium` crate:" +msgstr "" +"將 `:my_rust_lib` 新增至 GN `deps` 之後,我們仍需瞭解如何從 " +"`my_rust_lib_unittest.rs` 匯入及使用 `my_rust_lib`。我們尚未為 `my_rust_lib` " +"提供明確的 `crate_name`,因此系統會依據完整目標路徑和名稱來運算出 Crate 名" +"稱。幸好,我們可從自動匯入的 `chromium` Crate 中使用 `chromium::import!` 巨" +"集,避免採用這類不方便的名稱:" + +#: src/chromium/testing/chromium-import-macro.md +msgid "\"//ui/base:my_rust_lib\"" +msgstr "\"//ui/base:my_rust_lib\"" + +#: src/chromium/testing/chromium-import-macro.md +msgid "Under the covers the macro expands to something similar to:" +msgstr "在掩蓋之下,巨集會展開為類似如下的內容:" + +#: src/chromium/testing/chromium-import-macro.md +msgid "" +"More information can be found in [the doc comment](https://source.chromium." +"org/chromium/chromium/src/+/main:build/rust/chromium_prelude/" +"chromium_prelude.rs?q=f:chromium_prelude.rs%20pub.use.*%5Cbimport%5Cb;%20-f:" +"third_party&ss=chromium%2Fchromium%2Fsrc) of the `chromium::import` macro." +msgstr "" +"詳情請參閱 `chromium::import` 巨集的[文件註解](https://source.chromium.org/" +"chromium/chromium/src/+/main:build/rust/chromium_prelude/chromium_prelude.rs?" +"q=f:chromium_prelude.rs%20pub.use.*%5Cbimport%5Cb;%20-f:" +"third_party&ss=chromium%2Fchromium%2Fsrc)。" + +#: src/chromium/testing/chromium-import-macro.md +msgid "" +"`rust_static_library` supports specifying an explicit name via `crate_name` " +"property, but doing this is discouraged. And it is discouraged because the " +"crate name has to be globally unique. crates.io guarantees uniqueness of its " +"crate names so `cargo_crate` GN targets (generated by the `gnrt` tool " +"covered in a later section) use short crate names." +msgstr "" +"`rust_static_library` 支援透過 `crate_name` 屬性指定明確名稱,但不建議這麼" +"做。不建議的原因是 Crate 名稱在全域範圍內不得重複。crates.io 可保證其 Crate " +"名稱不重複,因此 `cargo_crate` GN 目標會使用簡短的 Crate 名稱。此目標是由後續" +"章節介紹的 `gnrt` 工具所產生。" + +#: src/exercises/chromium/testing.md +msgid "Testing exercise" +msgstr "測試練習" + +#: src/exercises/chromium/testing.md +msgid "Time for another exercise!" +msgstr "又到了練習時間!" + +#: src/exercises/chromium/testing.md +msgid "In your Chromium build:" +msgstr "在您的 Chromium 版本中:" + +#: src/exercises/chromium/testing.md +msgid "" +"Add a testable function next to `hello_from_rust`. Some suggestions: adding " +"two integers received as arguments, computing the nth Fibonacci number, " +"summing integers in a slice, etc." +msgstr "" +"在 `hello_from_rust` 旁邊新增可測試的函式。建議措施:新增兩個以引數形式接收的" +"整數、計算第 n 個費波那契數、加總切片中的整數等。" + +#: src/exercises/chromium/testing.md +msgid "Add a separate `..._unittest.rs` file with a test for the new function." +msgstr "新增獨立的 `..._unittest.rs` 檔案,內含新函式的測試。" + +#: src/exercises/chromium/testing.md +msgid "Add the new tests to `BUILD.gn`." +msgstr "將新測試新增至 `BUILD.gn`。" + +#: src/exercises/chromium/testing.md +msgid "Build the tests, run them, and verify that the new test works." +msgstr "建構並執行測試,確認新測試能正常運作。" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"The Rust community offers multiple options for C++/Rust interop, with new " +"tools being developed all the time. At the moment, Chromium uses a tool " +"called CXX." +msgstr "" +"Rust 社群提供多個 C++/Rust 互通性選項,並且會持續開發新工具。目前 Chromium 使" +"用的工具稱為 CXX。" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"You describe your whole language boundary in an interface definition " +"language (which looks a lot like Rust) and then CXX tools generate " +"declarations for functions and types in both Rust and C++." +msgstr "" +"您可以透過介面定義語言 (很類似 Rust) 描述整個語言邊界,然後 CXX 工具會為 " +"Rust 和 C++ 中的函式和型別產生宣告。" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"See the [CXX tutorial](https://cxx.rs/tutorial.html) for a full example of " +"using this." +msgstr "" +"如需完整的使用範例,請參閱 [CXX 教學課程](https://cxx.rs/tutorial.html)。" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"Talk through the diagram. Explain that behind the scenes, this is doing just " +"the same as you previously did. Point out that automating the process has " +"the following benefits:" +msgstr "" +"請完整講解圖表,說明背後的原理和先前的操作相同。請指出將程序自動化有以下優" +"點:" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"The tool guarantees that the C++ and Rust sides match (e.g. you get compile " +"errors if the `#[cxx::bridge]` doesn't match the actual C++ or Rust " +"definitions, but with out-of-sync manual bindings you'd get Undefined " +"Behavior)" +msgstr "" +"這項工具會保證 C++ 和 Rust 端相符。舉例來說,當 `#[cxx::bridge]` 與實際的 C+" +"+ 或 Rust 定義不相符,就會發生「編譯錯誤」,但如有未同步的手動繫結,則會發生" +"「未定義的行為」" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"The tool automates generation of FFI thunks (small, C-ABI-compatible, free " +"functions) for non-C features (e.g. enabling FFI calls into Rust or C++ " +"methods; manual bindings would require authoring such top-level, free " +"functions manually)" +msgstr "" +"這項工具會自動為非 C 功能產生 FFI 替換程式 (與 C-ABI 相容的小型、可自由使用的" +"函式),例如讓 FFI 呼叫 Rust 或 C++ 方法;手動繫結會需要手動編寫這類頂層的、可" +"自由使用的函式" + +#: src/chromium/interoperability-with-cpp.md +msgid "The tool and the library can handle a set of core types - for example:" +msgstr "這項工具和程式庫可處理一組核心型別,例如:" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"`&[T]` can be passed across the FFI boundary, even though it doesn't " +"guarantee any particular ABI or memory layout. With manual bindings `std::" +"span` / `&[T]` have to be manually destructured and rebuilt out of a " +"pointer and length - this is error-prone given that each language represents " +"empty slices slightly differently)" +msgstr "" +"`&[T]` 傳遞時可以跨越 FFI 邊界,但無法保證任何特定 ABI 或記憶體布局。使用手動" +"繫結時,`std::span`/`&[T]` 必須從一個指標和長度去手動解構並重新建構。這麼" +"做很容易出錯,因為每種語言各以略微不同的方式表示空切片" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"Smart pointers like `std::unique_ptr`, `std::shared_ptr`, and/or `Box` " +"are natively supported. With manual bindings, one would have to pass C-ABI-" +"compatible raw pointers, which would increase lifetime and memory-safety " +"risks." +msgstr "" +"`std::unique_ptr`、`std::shared_ptr` 和/或 `Box` 等智慧指標均可原生支" +"援。使用手動繫結時,必須傳遞與 C-ABI 相容的原始指標,這可能會增加生命週期和記" +"憶體安全風險。" + +#: src/chromium/interoperability-with-cpp.md +msgid "" +"`rust::String` and `CxxString` types understand and maintain differences in " +"string representation across the languages (e.g. `rust::String::lossy` can " +"build a Rust string from non-UTF8 input and `rust::String::c_str` can NUL-" +"terminate a string)." +msgstr "" +"`rust::String` 和 `CxxString` 型別可理解並維持各語言字串表示法的差異,例如 " +"`rust::String::lossy` 可透過非 UTF8 輸入內容建構 Rust 字串,而 `rust::" +"String::c_str` 可以空終止字串。" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "" +"CXX requires that the whole C++/Rust boundary is declared in `cxx::bridge` " +"modules inside `.rs` source code." +msgstr "CXX 要求在 `.rs` 原始碼的 `cxx::bridge` 模組中宣告整個 C++/Rust 邊界。" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "\"example/include/blobstore.h\"" +msgstr "\"example/include/blobstore.h\"" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "// Definitions of Rust types and functions go here\n" +msgstr "// 這裡放 Rust 型別和函式的定義\n" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "Point out:" +msgstr "請說明以下事項:" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "" +"Although this looks like a regular Rust `mod`, the `#[cxx::bridge]` " +"procedural macro does complex things to it. The generated code is quite a " +"bit more sophisticated - though this does still result in a `mod` called " +"`ffi` in your code." +msgstr "" +"雖然這看起來像一般的 Rust `mod`,但 `#[cxx::bridge]` 程序巨集會對其執行複雜作" +"業。產生的程式碼較為複雜,但仍會導致程式碼中出現名為 `ffi` 的 `mod`。" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "Native support for C++'s `std::unique_ptr` in Rust" +msgstr "Rust 中對 C++ `std::unique_ptr` 的原生支援" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "Native support for Rust slices in C++" +msgstr "C++ 中對 Rust 切片的原生支援" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "Calls from C++ to Rust, and Rust types (in the top part)" +msgstr "從 C++ 到 Rust 的呼叫,以及 Rust 型別 (頂部)" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "Calls from Rust to C++, and C++ types (in the bottom part)" +msgstr "從 Rust 到 C++ 的呼叫,以及 C++ 型別 (底部)" + +#: src/chromium/interoperability-with-cpp/example-bindings.md +msgid "" +"**Common misconception**: It _looks_ like a C++ header is being parsed by " +"Rust, but this is misleading. This header is never interpreted by Rust, but " +"simply `#include`d in the generated C++ code for the benefit of C++ " +"compilers." +msgstr "" +"**常見誤解**:它「看似」是由 Rust 剖析的 C++ 標頭,但這會造成誤導。這種標頭一" +"律不會由 Rust 解譯,只是為了 C++ 編譯器的好處,而在產生的 C++ 程式碼中設為 " +"`#include`。" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"By far the most useful page when using CXX is the [type reference](https://" +"cxx.rs/bindings.html)." +msgstr "使用 CXX 時,最實用的頁面是[型別參照](https://cxx.rs/bindings.html)。" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "CXX fundamentally suits cases where:" +msgstr "CXX 基本上適用下列情況:" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"Your Rust-C++ interface is sufficiently simple that you can declare all of " +"it." +msgstr "您的 Rust-C++ 介面非常簡單,您可以宣告其中所有項目。" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"You're using only the types natively supported by CXX already, for example " +"`std::unique_ptr`, `std::string`, `&[u8]` etc." +msgstr "" +"您只使用 CXX 已原生支援的型別,例如 `std::unique_ptr`、`std::string`、" +"`&[u8]` 等。" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"It has many limitations --- for example lack of support for Rust's `Option` " +"type." +msgstr "它有許多限制,例如不支援 Rust 的 `Option` 型別。" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"These limitations constrain us to using Rust in Chromium only for well " +"isolated \"leaf nodes\" rather than for arbitrary Rust-C++ interop. When " +"considering a use-case for Rust in Chromium, a good starting point is to " +"draft the CXX bindings for the language boundary to see if it appears simple " +"enough." +msgstr "" +"這些限制會導致我們只能在 Chromium 中將 Rust 用於妥善隔離的「葉節點」,而非用" +"於任意 Rust-C++ 互通情形。考慮 Chromium 中 Rust 的用途時,建議先草擬語言邊界" +"的 CXX 繫結,瞭解是否足夠簡單。" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"You should also discuss some of the other sticky points with CXX, for " +"example:" +msgstr "您也應討論一些 CXX 的其他棘手問題,例如:" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "" +"Its error handling is based around C++ exceptions (given on the next slide)" +msgstr "其錯誤處理方式是以 C++ 例外狀況為根據 (請見下一張投影片)" + +#: src/chromium/interoperability-with-cpp/limitations-of-cxx.md +msgid "Function pointers are awkward to use." +msgstr "函式指標不容易使用。" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "" +"CXX's [support for `Result`](https://cxx.rs/binding/result.html) relies " +"on C++ exceptions, so we can't use that in Chromium. Alternatives:" +msgstr "" +"CXX 的 [`Result` 支援](https://cxx.rs/binding/result.html)功能依賴 C++ " +"例外狀況,因此無法用於 Chromium。替代方案:" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "The `T` part of `Result` can be:" +msgstr "`Result` 的 `T` 部分可以是以下情形之一:" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "" +"Returned via out parameters (e.g. via `&mut T`). This requires that `T` can " +"be passed across the FFI boundary - for example `T` has to be:" +msgstr "" +"可透過傳出參數傳回,例如透過 `&mut T`。也就是說,`T` 必須能跨越 FFI 界線傳" +"遞,例如 `T` 必須符合下列條件:" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "A primitive type (like `u32` or `usize`)" +msgstr "是基本型別 (例如 `u32` 或 `usize`)" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "" +"A type natively supported by `cxx` (like `UniquePtr`) that has a suitable " +"default value to use in a failure case (_unlike_ `Box`)." +msgstr "" +"是 `cxx` 原生支援的型別 (就像 `UniquePtr`),具有可在失敗情況下使用的適當預" +"設值 (「不像」`Box`)。" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "" +"Retained on the Rust side, and exposed via reference. This may be needed " +"when `T` is a Rust type, which cannot be passed across the FFI boundary, and " +"cannot be stored in `UniquePtr`." +msgstr "" +"在 Rust 端保留,並透過參照公開。當 `T` 是 Rust 型別,無法跨越 FFI 邊界傳遞," +"且無法儲存在 `UniquePtr` 時,這就可能有必要。" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "The `E` part of `Result` can be:" +msgstr "`Result` 的 `E` 部分可以是以下情形之一:" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "" +"Returned as a boolean (e.g. `true` representing success, and `false` " +"representing failure)" +msgstr "傳回為布林值 (例如 `true` 代表成功,`false` 代表失敗)" + +#: src/chromium/interoperability-with-cpp/error-handling.md +msgid "" +"Preserving error details is in theory possible, but so far hasn't been " +"needed in practice." +msgstr "理論上可保留錯誤詳細資料,但目前在實際情況中並不需要。" + +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +msgid "CXX Error Handling: QR Example" +msgstr "CXX 錯誤處理:QR Code 範例" + +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +msgid "" +"The QR code generator is [an example](https://source.chromium.org/chromium/" +"chromium/src/+/main:components/qr_code_generator/qr_code_generator_ffi_glue." +"rs;l=13-18;drc=7bf1b75b910ca430501b9c6a74c1d18a0223ecca) where a boolean is " +"used to communicate success vs failure, and where the successful result can " +"be passed across the FFI boundary:" +msgstr "" +"在 QR code 產生器這個[範例](https://source.chromium.org/chromium/chromium/" +"src/+/main:components/qr_code_generator/qr_code_generator_ffi_glue.rs;" +"l=13-18;drc=7bf1b75b910ca430501b9c6a74c1d18a0223ecca)中,布林值是用來表示成功" +"與失敗,且成功結果可跨越 FFI 邊界傳遞:" + +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +msgid "\"qr_code_generator\"" +msgstr "\"qr_code_generator\"" + +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +msgid "" +"Students may be curious about the semantics of the `out_qr_size` output. " +"This is not the size of the vector, but the size of the QR code (and " +"admittedly it is a bit redundant - this is the square root of the size of " +"the vector)." +msgstr "" +"學生可能會想瞭解 `out_qr_size` 輸出內容的語意。這不是向量大小,而是 QR code " +"的大小 (誠然有點多餘,因為這是向量大小的平方根)。" + +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +msgid "" +"It may be worth pointing out the importance of initializing `out_qr_size` " +"before calling into the Rust function. Creation of a Rust reference that " +"points to uninitialized memory results in Undefined Behavior (unlike in C++, " +"when only the act of dereferencing such memory results in UB)." +msgstr "" +"可考慮說明先初始化 `out_qr_size` 再呼叫 Rust 函式的重要性。建立指向未初始化記" +"憶體的 Rust 參照時,會導致「未定義的行為」(不同的是,在 C++ 中只有解除參照這" +"類記憶體時才會導致「未定義的行為」)。" + +#: src/chromium/interoperability-with-cpp/error-handling-qr.md +msgid "" +"If students ask about `Pin`, then explain why CXX needs it for mutable " +"references to C++ data: the answer is that C++ data can’t be moved around " +"like Rust data, because it may contain self-referential pointers." +msgstr "" +"如有學生詢問 `Pin`,請說明為何 CXX 需要這個項目來處理 C++ 資料的可變動參照:" +"答案是因為 C++ 資料可能包含自我參照指標,無法像 Rust 資料一樣移動。" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "CXX Error Handling: PNG Example" +msgstr "CXX 錯誤處理:PNG 範例" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "" +"A prototype of a PNG decoder illustrates what can be done when the " +"successful result cannot be passed across the FFI boundary:" +msgstr "" +"PNG 解碼器的原型可說明當成功的結果無法跨越 FFI 邊界時,可以執行哪些操作:" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "\"gfx::rust_bindings\"" +msgstr "\"gfx::rust_bindings\"" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "" +"/// This returns an FFI-friendly equivalent of `Result,\n" +" /// ()>`.\n" +msgstr "/// 這回傳一個 FFI 友好的型別,等同於 `Result, ()>`.\n" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "/// C++ bindings for the `crate::png::ResultOfPngReader` type.\n" +msgstr "/// `crate::png::ResultOfPngReader` 型別的 C++ 繫結:\n" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "/// C++ bindings for the `crate::png::PngReader` type.\n" +msgstr "/// `crate::png::PngReader` 型別的 C++ 繫結:\n" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "" +"`PngReader` and `ResultOfPngReader` are Rust types --- objects of these " +"types cannot cross the FFI boundary without indirection of a `Box`. We " +"can't have an `out_parameter: &mut PngReader`, because CXX doesn't allow C++ " +"to store Rust objects by value." +msgstr "" +"`PngReader` 和 `ResultOfPngReader` 是 Rust 型別,這些型別的物件必須採用 " +"`Box` 的間接機制,才能跨越 FFI 邊界。我們無法使用 `out_parameter: &mut " +"PngReader`,因為 CXX 不允許 C++ 依據值儲存 Rust 物件。" + +#: src/chromium/interoperability-with-cpp/error-handling-png.md +msgid "" +"This example illustrates that even though CXX doesn't support arbitrary " +"generics nor templates, we can still pass them across the FFI boundary by " +"manually specializing / monomorphizing them into a non-generic type. In the " +"example `ResultOfPngReader` is a non-generic type that forwards into " +"appropriate methods of `Result` (e.g. into `is_err`, `unwrap`, and/or " +"`as_mut`)." +msgstr "" +"本範例說明即使 CXX 不支援任意泛型和範本,我們還是可以手動將這些範本特化/單型" +"化為非泛型型別,傳遞到 FFI 邊界。在範例中,`ResultOfPngReader` 屬於非泛型型" +"別,會轉送至適當的 `Result` 方法,例如 `is_err`、`unwrap` 和/或 " +"`as_mut`。" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "Using cxx in Chromium" +msgstr "在 Chromium 中使用 CXX" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "" +"In Chromium, we define an independent `#[cxx::bridge] mod` for each leaf-" +"node where we want to use Rust. You'd typically have one for each " +"`rust_static_library`. Just add" +msgstr "" +"在 Chromium 中,我們會為每個要使用 Rust 的葉節點定義獨立的 `#[cxx::bridge] " +"mod`。每個 `rust_static_library` 通常都需要一個值。只要將下列項目" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "" +"```gn\n" +"cxx_bindings = [ \"my_rust_file.rs\" ]\n" +" # list of files containing #[cxx::bridge], not all source files\n" +"allow_unsafe = true\n" +"```" +msgstr "" +"```gn\n" +"cxx_bindings = [ \"my_rust_file.rs\" ]\n" +" # 含有 #[cxx::bridge] 的檔案列表,而非所有原始碼檔案\n" +"allow_unsafe = true\n" +"```" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "" +"to your existing `rust_static_library` target alongside `crate_root` and " +"`sources`." +msgstr "" +"新增至現有的 `rust_static_library` 目標,並搭配 `crate_root` 和 `sources`。" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "C++ headers will be generated at a sensible location, so you can just" +msgstr "C++ 標頭會在合理位置產生,因此您只需採用下列程式碼:" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "\"ui/base/my_rust_file.rs.h\"" +msgstr "\"ui/base/my_rust_file.rs.h\"" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "" +"You will find some utility functions in `//base` to convert to/from Chromium " +"C++ types to CXX Rust types --- for example [`SpanToRustSlice`](https://" +"source.chromium.org/chromium/chromium/src/+/main:base/containers/span_rust.h;" +"l=21)." +msgstr "" +"您會在 `//base` 中發現一些公用函式,可將 Chromium C++ 型別轉換成 CXX Rust 型" +"別,逆向轉換也可以,例如 [`SpanToRustSlice`](https://source.chromium.org/" +"chromium/chromium/src/+/main:base/containers/span_rust.h;l=21)。" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "Students may ask --- why do we still need `allow_unsafe = true`?" +msgstr "學生可能會問:為何仍需要 `allow_unsafe = true`?" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "" +"The broad answer is that no C/C++ code is \"safe\" by the normal Rust " +"standards. Calling back and forth to C/C++ from Rust may do arbitrary things " +"to memory, and compromise the safety of Rust's own data layouts. Presence of " +"_too many_ `unsafe` keywords in C/C++ interop can harm the signal-to-noise " +"ratio of such a keyword, and is [controversial](https://steveklabnik.com/" +"writing/the-cxx-debate), but strictly, bringing any foreign code into a Rust " +"binary can cause unexpected behavior from Rust's perspective." +msgstr "" +"籠統的答案是根據一般 Rust 標準,任何 C/C++ 程式碼都不「安全」。從 Rust 來回呼" +"叫 C/C++ 可能會對記憶體執行任何作業,進而破壞 Rust 本身資料布局的安全性。在 " +"C/C++ 互通性中如果出現「過多」`unsafe` 關鍵字,可能會傷害這類關鍵字的訊噪比," +"且[具有爭議性](https://steveklabnik.com/writing/the-cxx-debate),但嚴格來說," +"在 Rust 二進位檔中導入任何外來程式碼,都可能對 Rust 造成非預期行為。" + +#: src/chromium/interoperability-with-cpp/using-cxx-in-chromium.md +msgid "" +"The narrow answer lies in the diagram at the top of [this page](../" +"interoperability-with-cpp.md) --- behind the scenes, CXX generates Rust " +"`unsafe` and `extern \"C\"` functions just like we did manually in the " +"previous section." +msgstr "" +"詳細答案位於[這個頁面](../interoperability-with-cpp.md)頂端的圖表中:CXX 會在" +"幕後產生 Rust `unsafe` 和 `extern \"C\"` 函式,如同前一節中的手動操作。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Exercise: Interoperability with C++" +msgstr "練習:與 C++ 的互通性" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Part one" +msgstr "第一部分" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"In the Rust file you previously created, add a `#[cxx::bridge]` which " +"specifies a single function, to be called from C++, called " +"`hello_from_rust`, taking no parameters and returning no value." +msgstr "" +"在您先前建立的 Rust 檔案中新增 `#[cxx::bridge]`,指定要從 C++ 呼叫的單一函式 " +"(名為 `hello_from_rust`),但不採用任何參數,也不會傳回值。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"Modify your previous `hello_from_rust` function to remove `extern \"C\"` and " +"`#[no_mangle]`. This is now just a standard Rust function." +msgstr "" +"修改先前的 `hello_from_rust` 函式,移除 `extern \"C\"` 和 `#[no_mangle]`。現" +"在這樣就只是標準的 Rust 函式。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Modify your `gn` target to build these bindings." +msgstr "修改 `gn` 目標,建構這些繫結。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"In your C++ code, remove the forward-declaration of `hello_from_rust`. " +"Instead, include the generated header file." +msgstr "" +"在 C++ 程式碼中,移除 `hello_from_rust` 的前向宣告,改為納入產生的標頭檔案。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Build and run!" +msgstr "建構並執行!" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Part two" +msgstr "第二部分" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"It's a good idea to play with CXX a little. It helps you think about how " +"flexible Rust in Chromium actually is." +msgstr "您可以試著玩玩 CXX,這有助於瞭解 Chromium 中的 Rust 有多靈活。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Some things to try:" +msgstr "可嘗試的事項:" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Call back into C++ from Rust. You will need:" +msgstr "從 Rust 呼叫 C++。您會需要以下項目:" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"An additional header file which you can `include!` from your `cxx::bridge`. " +"You'll need to declare your C++ function in that new header file." +msgstr "" +"額外的標頭檔案,可從 `cxx::bridge` 中 `include!`。您會需要在新標頭檔案中宣告 " +"C++ 函式。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"An `unsafe` block to call such a function, or alternatively specify the " +"`unsafe` keyword in your `#[cxx::bridge]` [as described here](https://cxx.rs/" +"extern-c++.html#functions-and-member-functions)." +msgstr "" +"用於呼叫這類函式的 `unsafe` 區塊,或者可在 `#[cxx::bridge]` 中指定 `unsafe` " +"關鍵字,[如這個頁面所述](https://cxx.rs/extern-c++.html#functions-and-member-" +"functions)。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"You may also need to `#include \"third_party/rust/cxx/v1/crate/include/cxx." +"h\"`" +msgstr "" +"您可能也需要 `#include \"third_party/rust/cxx/v1/crate/include/cxx.h\"`" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Pass a C++ string from C++ into Rust." +msgstr "將 C++ 字串從 C++ 傳遞至 Rust。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Pass a reference to a C++ object into Rust." +msgstr "將 C++ 物件的參照傳遞至 Rust。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"Intentionally get the Rust function signatures mismatched from the `#[cxx::" +"bridge]`, and get used to the errors you see." +msgstr "" +"刻意從 `#[cxx::bridge]` 中,取得不相符的 Rust 函式簽章,並熟悉看到的錯誤。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"Intentionally get the C++ function signatures mismatched from the `#[cxx::" +"bridge]`, and get used to the errors you see." +msgstr "" +"刻意從 `#[cxx::bridge]` 中取得不相符的 C++ 函式簽章,並熟悉看到的錯誤。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"Pass a `std::unique_ptr` of some type from C++ into Rust, so that Rust can " +"own some C++ object." +msgstr "" +"將某些型別的 `std::unique_ptr` 從 C++ 傳遞至 Rust,這樣 Rust 就能擁有某些 C+" +"+ 物件。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"Create a Rust object and pass it into C++, so that C++ owns it. (Hint: you " +"need a `Box`)." +msgstr "" +"建立 Rust 物件並傳遞至 C++ 中,讓 C++ 擁有該物件 (提示:您需要 `Box`)。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Declare some methods on a C++ type. Call them from Rust." +msgstr "在 C++ 型別上宣告一些方法,然後從 Rust 呼叫。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Declare some methods on a Rust type. Call them from C++." +msgstr "在 Rust 型別上宣告一些方法,然後從 C++ 呼叫。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Part three" +msgstr "第三部分" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"Now you understand the strengths and limitations of CXX interop, think of a " +"couple of use-cases for Rust in Chromium where the interface would be " +"sufficiently simple. Sketch how you might define that interface." +msgstr "" +"現在您已瞭解 CXX 互通性的優勢和限制,不妨思考一些 Chromium 中介面相當簡單的 " +"Rust 用途。草擬定義該介面的方式。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "The [`cxx` binding reference](https://cxx.rs/bindings.html)" +msgstr "[`cxx` 繫結參照](https://cxx.rs/bindings.html)" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"The [`rust_static_library` gn template](https://source.chromium.org/chromium/" +"chromium/src/+/main:build/rust/rust_static_library.gni;l=16)" +msgstr "" +"[`rust_static_library` gn 範本](https://source.chromium.org/chromium/" +"chromium/src/+/main:build/rust/rust_static_library.gni;l=16)" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "Some of the questions you may encounter:" +msgstr "您可能會遇到以下問題:" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"I'm seeing a problem initializing a variable of type X with type Y, where X " +"and Y are both function types. This is because your C++ function doesn't " +"quite match the declaration in your `cxx::bridge`." +msgstr "" +"當 X 和 Y 都是函式型別,初始化型別 X 的變數和型別 Y 時會發生問題。這是因為 C+" +"+ 函式與 `cxx::bridge` 中的宣告不太相符。" + +#: src/exercises/chromium/interoperability-with-cpp.md +msgid "" +"I seem to be able to freely convert C++ references into Rust references. " +"Doesn't that risk UB? For CXX's _opaque_ types, no, because they are zero-" +"sized. For CXX trivial types yes, it's _possible_ to cause UB, although " +"CXX's design makes it quite difficult to craft such an example." +msgstr "" +"我似乎可將 C++ 參照任意轉換為 Rust 參照。這樣不就可能造成 UB 嗎?若是 CXX 的" +"「opaque」型別就不會,因為這種型別的大小為零。CXX 中的 trivial 型別則「有可" +"能」造成 UB,雖然 CXX 的設計讓撰寫這類範例相當困難。" + +#: src/chromium/adding-third-party-crates.md +msgid "" +"Rust libraries are called \"crates\" and are found at [crates.io](https://" +"crates.io). It's _very easy_ for Rust crates to depend upon one another. So " +"they do!" +msgstr "" +"Rust 程式庫稱為「Crate」,位於 [crates.io](https://crates.io)。Rust Crate「非" +"常容易」互相依附,所以它們也確實常常這麼做!" + +#: src/chromium/adding-third-party-crates.md +msgid "C++ library" +msgstr "C++ 函式庫" + +#: src/chromium/adding-third-party-crates.md +msgid "Rust crate" +msgstr "Rust crate" + +#: src/chromium/adding-third-party-crates.md +msgid "Build system" +msgstr "建構系統" + +#: src/chromium/adding-third-party-crates.md +msgid "Lots" +msgstr "非常多" + +#: src/chromium/adding-third-party-crates.md +msgid "Consistent: `Cargo.toml`" +msgstr "一致:`Cargo.toml`" + +#: src/chromium/adding-third-party-crates.md +msgid "Typical library size" +msgstr "一般程式庫大小" + +#: src/chromium/adding-third-party-crates.md +msgid "Large-ish" +msgstr "偏大" + +#: src/chromium/adding-third-party-crates.md +msgid "Small" +msgstr "小" + +#: src/chromium/adding-third-party-crates.md +msgid "Transitive dependencies" +msgstr "遞移依附元件" + +#: src/chromium/adding-third-party-crates.md +msgid "Few" +msgstr "很少" + +#: src/chromium/adding-third-party-crates.md +msgid "For a Chromium engineer, this has pros and cons:" +msgstr "對 Chromium 工程師來說,這有以下優缺點:" + +#: src/chromium/adding-third-party-crates.md +msgid "" +"All crates use a common build system so we can automate their inclusion into " +"Chromium..." +msgstr "所有 Crate 都使用通用的建構系統,因此我們可以自動將其納入 Chromium..." + +#: src/chromium/adding-third-party-crates.md +msgid "" +"... but, crates typically have transitive dependencies, so you will likely " +"have to bring in multiple libraries." +msgstr "...但 Crate 通常具有遞移依附元件,因此可能需要導入多個程式庫。" + +#: src/chromium/adding-third-party-crates.md +msgid "We'll discuss:" +msgstr "我們將探討以下內容:" + +#: src/chromium/adding-third-party-crates.md +msgid "How to put a crate in the Chromium source code tree" +msgstr "如何在 Chromium 原始碼樹中加入 Crate" + +#: src/chromium/adding-third-party-crates.md +msgid "How to make `gn` build rules for it" +msgstr "如何為其建立 `gn` 建構規則" + +#: src/chromium/adding-third-party-crates.md +msgid "How to audit its source code for sufficient safety." +msgstr "如何稽核原始碼,確保足夠安全" + +#: src/chromium/adding-third-party-crates/configuring-cargo-toml.md +msgid "Configuring the `Cargo.toml` file to add crates" +msgstr "設定 `Cargo.toml` 檔案以新增 Crate" + +#: src/chromium/adding-third-party-crates/configuring-cargo-toml.md +msgid "" +"Chromium has a single set of centrally-managed direct crate dependencies. " +"These are managed through a single [`Cargo.toml`](https://source.chromium." +"org/chromium/chromium/src/+/main:third_party/rust/chromium_crates_io/Cargo." +"toml):" +msgstr "" +"Chromium 有一組集中管理的直接 Crate 依附元件。這些元件可透過單一 [`Cargo." +"toml`](https://source.chromium.org/chromium/chromium/src/+/main:third_party/" +"rust/chromium_crates_io/Cargo.toml) 管理:" + +#: src/chromium/adding-third-party-crates/configuring-cargo-toml.md +msgid "" +"```toml\n" +"[dependencies]\n" +"bitflags = \"1\"\n" +"cfg-if = \"1\"\n" +"cxx = \"1\"\n" +"# lots more...\n" +"```" +msgstr "" +"```toml\n" +"[dependencies]\n" +"bitflags = \"1\"\n" +"cfg-if = \"1\"\n" +"cxx = \"1\"\n" +"# 還有更多...\n" +"```" + +#: src/chromium/adding-third-party-crates/configuring-cargo-toml.md +msgid "" +"As with any other `Cargo.toml`, you can specify [more details about the " +"dependencies](https://doc.rust-lang.org/cargo/reference/specifying-" +"dependencies.html) --- most commonly, you'll want to specify the `features` " +"that you wish to enable in the crate." +msgstr "" +"與任何其他 `Cargo.toml` 一樣,您可以指定[依附元件的更多詳細資料](https://doc." +"rust-lang.org/cargo/reference/specifying-dependencies.html)。以最常見的情況來" +"說,您會想在 Crate 中指定要啟用的 `features`。" + +#: src/chromium/adding-third-party-crates/configuring-cargo-toml.md +msgid "" +"When adding a crate to Chromium, you'll often need to provide some extra " +"information in an additional file, `gnrt_config.toml`, which we'll meet next." +msgstr "" +"將 Crate 新增至 Chromium 時,您通常需要在 `gnrt_config.toml` 這個額外檔案中提" +"供額外資訊,這接下來會介紹。" + +#: src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +msgid "" +"Alongside `Cargo.toml` is [`gnrt_config.toml`](https://source.chromium.org/" +"chromium/chromium/src/+/main:third_party/rust/chromium_crates_io/gnrt_config." +"toml). This contains Chromium-specific extensions to crate handling." +msgstr "" +"除了 `Cargo.toml`,還有 [`gnrt_config.toml`](https://source.chromium.org/" +"chromium/chromium/src/+/main:third_party/rust/chromium_crates_io/gnrt_config." +"toml)。這包含用來處理 Crate 的 Chromium 專屬擴充功能。" + +#: src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +msgid "" +"If you add a new crate, you should specify at least the `group`. This is one " +"of:" +msgstr "新增 Crate 時,應至少指定 `group`,可以是以下其中一個:" + +#: src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +#: src/chromium/adding-third-party-crates/depending-on-a-crate.md +msgid "For instance," +msgstr "舉例來說:" + +#: src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +msgid "" +"Depending on the crate source code layout, you may also need to use this " +"file to specify where its `LICENSE` file(s) can be found." +msgstr "" +"視 Crate 原始碼布局而定,您可能也需要使用這個檔案指定其 `LICENSE 檔案的位置。" + +#: src/chromium/adding-third-party-crates/configuring-gnrt-config-toml.md +msgid "" +"Later, we'll see some other things you will need to configure in this file " +"to resolve problems." +msgstr "稍後我們會看到一些其他您需在這個檔案中設定的項目,才能解決問題。" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "" +"A tool called `gnrt` knows how to download crates and how to generate `BUILD." +"gn` rules." +msgstr "`gnrt` 這項工具瞭解如何下載 Crate,以及如何產生 `BUILD.gn` 規則。" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "To start, download the crate you want like this:" +msgstr "首先,請按照以下方式下載任何你想要的 Crate:" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "" +"Although the `gnrt` tool is part of the Chromium source code, by running " +"this command you will be downloading and running its dependencies from " +"`crates.io`. See [the earlier section](../cargo.md) discussing this security " +"decision." +msgstr "" +"雖然 `gnrt` 工具屬於 Chromium 原始碼的一部分,但透過執行這項指令,您可以從 " +"`crates.io` 下載並執行其依附元件。請參閱[前面的章節](../cargo.md)中有關這項安" +"全性決策的討論。" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "This `vendor` command may download:" +msgstr "這項 `vendor` 指令可能會下載以下項目:" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "Your crate" +msgstr "您的 Crate" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "Direct and transitive dependencies" +msgstr "直接依附元件和遞移依附元件" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "" +"New versions of other crates, as required by `cargo` to resolve the complete " +"set of crates required by Chromium." +msgstr "" +"其他 Crate 的新版本。這是 `cargo` 的要求,以便解析 Chromium 所需的完整 Crate " +"組合。" + +#: src/chromium/adding-third-party-crates/downloading-crates.md +msgid "" +"Chromium maintains patches for some crates, kept in `//third_party/rust/" +"chromium_crates_io/patches`. These will be reapplied automatically, but if " +"patching fails you may need to take manual action." +msgstr "" +"Chromium 會維護部分 Crate 的修補程式,保留在 `//third_party/rust/" +"chromium_crates_io/patches` 中。系統會自動重新套用這些設定,但如果修補失敗," +"就可能需要手動操作。" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "" +"Once you've downloaded the crate, generate the `BUILD.gn` files like this:" +msgstr "下載 Crate 後,請如下產生 `BUILD.gn` 檔案:" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "Now run `git status`. You should find:" +msgstr "現在請執行 `git status`,您應會看到以下情形:" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "" +"At least one new crate source code in `third_party/rust/chromium_crates_io/" +"vendor`" +msgstr "" +"在 `third_party/rust/chromium_crates_io/vendor` 中,至少有一個新的 Crate 原始" +"碼" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "" +"At least one new `BUILD.gn` in `third_party/rust//v`" +msgstr "" +"在 `third_party/rust//v` 中,至少有一個新" +"的 `BUILD.gn`" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "An appropriate `README.chromium`" +msgstr "適當的 `README.chromium`" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "" +"The \"major semver version\" is a [Rust \"semver\" version number](https://" +"doc.rust-lang.org/cargo/reference/semver.html)." +msgstr "" +"「major semver version」是 [Rust「Semver」版本號碼](https://doc.rust-lang." +"org/cargo/reference/semver.html)." + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "" +"Take a close look, especially at the things generated in `third_party/rust`." +msgstr "請仔細查看,尤其是 `third_party/rust` 中產生的內容。" + +#: src/chromium/adding-third-party-crates/generating-gn-build-rules.md +msgid "" +"Talk a little about semver --- and specifically the way that in Chromium " +"it's to allow multiple incompatible versions of a crate, which is " +"discouraged but sometimes necessary in the Cargo ecosystem." +msgstr "" +"請稍微介紹一下 Semver,並具體說明在 Chromium 中,Semver 可允許多種不相容的 " +"Crate 版本。這不是建議做法,但在 Cargo 生態系統中有時是必要的。" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "" +"If your build fails, it may be because of a `build.rs`: programs which do " +"arbitrary things at build time. This is fundamentally at odds with the " +"design of `gn` and `ninja` which aim for static, deterministic, build rules " +"to maximize parallelism and repeatability of builds." +msgstr "" +"如果建構失敗,可能是因為 `build.rs`,這類程式會在建構期間執行任意操作。根本而" +"言,這不符合 `gn` 和 `ninja` 的設計,後者的目標是達成靜態的確定性建構規則,盡" +"可能提高建構作業的平行處理程度和重複性。" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "" +"Some `build.rs` actions are automatically supported; others require action:" +msgstr "有些 `build.rs` 動作可自動支援,有些則需要進一步操作:" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "build script effect" +msgstr "建構指令碼效果" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Supported by our gn templates" +msgstr "gn 範本是否支援" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Work required by you" +msgstr "您需要做的" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Checking rustc version to configure features on and off" +msgstr "檢查 rustc 版本,將功能設為開啟/關閉" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "None" +msgstr "無" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Checking platform or CPU to configure features on and off" +msgstr "檢查平台或 CPU,將功能設為開啟/關閉" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Generating code" +msgstr "產生程式碼" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Yes - specify in `gnrt_config.toml`" +msgstr "是 - 在 `gnrt_config.toml` 中指定" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Building C/C++" +msgstr "建構 C/C++" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Patch around it" +msgstr "撰寫修補程式" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "Arbitrary other actions" +msgstr "任意其他動作" + +#: src/chromium/adding-third-party-crates/resolving-problems.md +msgid "" +"Fortunately, most crates don't contain a build script, and fortunately, most " +"build scripts only do the top two actions." +msgstr "" +"幸運的是,大部分 Crate 均不包含建構指令碼,而大部分建構指令碼只會執行前兩項動" +"作。" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md +msgid "" +"If `ninja` complains about missing files, check the `build.rs` to see if it " +"writes source code files." +msgstr "如果 `ninja` 抱怨缺少檔案,請查看 `build.rs`,確認是否寫入原始碼檔案。" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md +msgid "" +"If so, modify [`gnrt_config.toml`](../configuring-gnrt-config-toml.md) to " +"add `build-script-outputs` to the crate. If this is a transitive dependency, " +"that is, one on which Chromium code should not directly depend, also add " +"`allow-first-party-usage=false`. There are several examples already in that " +"file:" +msgstr "" +"如果是,請修改 [`gnrt_config.toml`](../configuring-gnrt-config-toml.md),將 " +"`build-script-outputs` 新增至 Crate。若是遞移依附元件,也就是 Chromium 程式" +"碼 不應直接依附的依附元件,請一併加上 `allow-first-party-usage=false`。該檔案" +"中已有幾個範例:" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md +msgid "" +"```toml\n" +"[crate.unicode-linebreak]\n" +"allow-first-party-usage = false\n" +"build-script-outputs = [\"tables.rs\"]\n" +"```" +msgstr "" +"```toml\n" +"[crate.unicode-linebreak]\n" +"allow-first-party-usage = false\n" +"build-script-outputs = [\"tables.rs\"]\n" +"```" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-generate-code.md +msgid "" +"Now rerun [`gnrt.py -- gen`](../generating-gn-build-rules.md) to regenerate " +"`BUILD.gn` files to inform ninja that this particular output file is input " +"to subsequent build steps." +msgstr "" +"現在請重新執行 [`gnrt.py -- gen`](../generating-gn-build-rules.md),重新產生 " +"`BUILD.gn` 檔案以通知 ninja 這個輸出檔案會輸入至後續建構步驟。" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +msgid "" +"Some crates use the [`cc`](https://crates.io/crates/cc) crate to build and " +"link C/C++ libraries. Other crates parse C/C++ using [`bindgen`](https://" +"crates.io/crates/bindgen) within their build scripts. These actions can't be " +"supported in a Chromium context --- our gn, ninja and LLVM build system is " +"very specific in expressing relationships between build actions." +msgstr "" +"部分 Crate 使用 [`cc`](https://crates.io/crates/cc) Crate 建構和連結 C/C++ 程" +"式庫。其他 Crate 在建構指令碼中使用 [`bindgen`](https://crates.io/crates/" +"bindgen) 剖析 C/C++。Chromium 環境無法支援這些動作,因為我們的 gn、ninja 和 " +"LLVM 建構系統特別要求明確表達建構動作之間的關係。" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +msgid "So, your options are:" +msgstr "因此,您有以下選擇:" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +msgid "Avoid these crates" +msgstr "避開這類 Crate" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +msgid "Apply a patch to the crate." +msgstr "將修補程式套用至 Crate。" + +#: src/chromium/adding-third-party-crates/resolving-problems/build-scripts-which-take-arbitrary-actions.md +msgid "" +"Patches should be kept in `third_party/rust/chromium_crates_io/patches/" +"` - see for example the [patches against the `cxx` crate](https://" +"source.chromium.org/chromium/chromium/src/+/main:third_party/rust/" +"chromium_crates_io/patches/cxx/) - and will be applied automatically by " +"`gnrt` each time it upgrades the crate." +msgstr "" +"修補程式應保留在 `third_party/rust/chromium_crates_io/patches/` 中,範" +"例請見 [`cxx` Crate 的修補程式](https://source.chromium.org/chromium/" +"chromium/src/+/main:third_party/rust/chromium_crates_io/patches/cxx。此外,在" +"每次升級 Crate 時,修補補程式會由 `gnrt` 自動套用。" + +#: src/chromium/adding-third-party-crates/depending-on-a-crate.md +msgid "" +"Once you've added a third-party crate and generated build rules, depending " +"on a crate is simple. Find your `rust_static_library` target, and add a " +"`dep` on the `:lib` target within your crate." +msgstr "" +"新增第三方 Crate 並產生建構規則後,依附 Crate 就很簡單。請找出 " +"`rust_static_library` 目標,然後在 Crate 的 `:lib` 目標中新增 `dep`。" + +#: src/chromium/adding-third-party-crates/depending-on-a-crate.md +#, fuzzy +msgid "Specifically," +msgstr "特定 OS" + +#: src/chromium/adding-third-party-crates/depending-on-a-crate.md +msgid "" +"```bob\n" +" +------------+ +----------------------+\n" +"\"//third_party/rust\" | crate name | \"/v\" | major semver version | \":" +"lib\"\n" +" +------------+ +----------------------+\n" +"```" +msgstr "" +"```bob\n" +" +------------+ +----------------------+\n" +"\"//third_party/rust\" | crate name | \"/v\" | major semver version | \":" +"lib\"\n" +" +------------+ +----------------------+\n" +"```" + +#: src/chromium/adding-third-party-crates/depending-on-a-crate.md +msgid "" +"```gn\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [ \"lib.rs\" ]\n" +" deps = [ \"//third_party/rust/example_rust_crate/v1:lib\" ]\n" +"}\n" +"```" +msgstr "" +"```gn\n" +"rust_static_library(\"my_rust_lib\") {\n" +" crate_root = \"lib.rs\"\n" +" sources = [ \"lib.rs\" ]\n" +" deps = [ \"//third_party/rust/example_rust_crate/v1:lib\" ]\n" +"}\n" +"```" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "Auditing Third Party Crates" +msgstr "稽核第三方 Crate" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Adding new libraries is subject to Chromium's standard [policies](https://" +"chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/rust." +"md#Third_party-review), but of course also subject to security review. As " +"you may be bringing in not just a single crate but also transitive " +"dependencies, there may be a lot of code to review. On the other hand, safe " +"Rust code can have limited negative side effects. How should you review it?" +msgstr "" +"新增程式庫時必須遵守 Chromium 的標準[政策](https://chromium.googlesource.com/" +"chromium/src/+/refs/heads/main/docs/rust.md#Third_party-review),不過當然也須" +"接受安全性審查。您可能不只引入一個 Crate,還會傳入遞移依附元件,因此可能有許" +"多程式碼需要審查。另一方面,安全的 Rust 程式碼不會產生多少負面副作用。應如何" +"審查呢?" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Over time Chromium aims to move to a process based around [cargo vet]" +"(https://mozilla.github.io/cargo-vet/)." +msgstr "" +"隨著時間推移,Chromium 的目標是移至以 [cargo vet](https://mozilla.github.io/" +"cargo-vet/) 為基礎的程序。" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Meanwhile, for each new crate addition, we are checking for the following:" +msgstr "同時,我們會針對每個新增的 Crate 檢查以下項目:" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Understand why each crate is used. What's the relationship between crates? " +"If the build system for each crate contains a `build.rs` or procedural " +"macros, work out what they're for. Are they compatible with the way Chromium " +"is normally built?" +msgstr "" +"瞭解使用各個 Crate 的原因。Crate 之間的關係為何?如果每個 Crate 的建構系統都" +"包含 `build.rs` 或程序巨集,請思考 Crate 的用途。這些 Crate 是否與 Chromium " +"平常的建構方式相容?" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "Check each crate seems to be reasonably well maintained" +msgstr "檢查每個 Crate 的維護情況是否合理良好" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Use `cd third-party/rust/chromium_crates_io; cargo audit` to check for known " +"vulnerabilities (first you'll need to `cargo install cargo-audit`, which " +"ironically involves downloading lots of dependencies from the internet[2](../" +"cargo.md))" +msgstr "" +"使用 `cd third-party/rust/chromium_crates_io; cargo audit` 檢查是否有已知的安" +"全漏洞 (您首先需要執行 `cargo install cargo-audit`,諷刺的是,這麼做需要從網" +"際網路下載大量依附元件[2](../cargo.md))" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Ensure any `unsafe` code is good enough for the [Rule of Two](https://" +"chromium.googlesource.com/chromium/src/+/main/docs/security/rule-of-2." +"md#unsafe-code-in-safe-languages)" +msgstr "" +"確保所有 `unsafe` 程式碼都妥善符合[兩個項目的規則](https://chromium." +"googlesource.com/chromium/src/+/main/docs/security/rule-of-2.md#unsafe-code-" +"in-safe-languages)" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "Check for any use of `fs` or `net` APIs" +msgstr "檢查是否使用 `fs` 或 `net` API" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"Read all the code at a sufficient level to look for anything out of place " +"that might have been maliciously inserted. (You can't realistically aim for " +"100% perfection here: there's often just too much code.)" +msgstr "" +"請在足夠的層級閱讀所有程式碼,檢查是否出現任何可能是惡意插入的錯誤內容 (實務" +"上很難達到 100% 完美的成果,畢竟通常會有太多程式碼。)" + +#: src/chromium/adding-third-party-crates/reviews-and-audits.md +msgid "" +"These are just guidelines --- work with reviewers from `security@chromium." +"org` to work out the right way to become confident of the crate." +msgstr "" +"上述內容只是指南,請與 `security@chromium.org` 的審查人員合作,瞭解如何正確地" +"確保 Crate 是可信的。" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "Checking Crates into Chromium Source Code" +msgstr "將 Crate 登錄為 Chromium 原始碼" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "`git status` should reveal:" +msgstr "`git status` 應會顯示以下內容:" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "Crate code in `//third_party/rust/chromium_crates_io`" +msgstr "`//third_party/rust/chromium_crates_io` 中的 Crate 程式碼" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "" +"Metadata (`BUILD.gn` and `README.chromium`) in `//third_party/rust//" +"`" +msgstr "" +"`//third_party/rust//` 中的中繼資料 (`BUILD.gn` 和 `README." +"chromium`)" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "Please also add an `OWNERS` file in the latter location." +msgstr "請一併在後者的位置中新增 `OWNERS` 檔案。" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "" +"You should land all this, along with your `Cargo.toml` and `gnrt_config." +"toml` changes, into the Chromium repo." +msgstr "" +"請務必在 Chromium 存放區中放入所有這些項目,以及 `Cargo.toml` 和 " +"`gnrt_config.toml` 變更內容。" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "" +"**Important**: you need to use `git add -f` because otherwise `.gitignore` " +"files may result in some files being skipped." +msgstr "" +"**重要事項**:請務必使用 `git add -f`,否則 `.gitignore` 檔案可能會導致某些檔" +"案遭到略過。" + +#: src/chromium/adding-third-party-crates/checking-in.md +msgid "" +"As you do so, you might find presubmit checks fail because of non-inclusive " +"language. This is because Rust crate data tends to include names of git " +"branches, and many projects still use non-inclusive terminology there. So " +"you may need to run:" +msgstr "" +"這時,預先提交的檢查作業可能會因使用非包容性的語言而失敗。這是因為 Rust " +"Crate 資料通常會包含 Git 分支版本的名稱,而許多專案仍使用非包容性的術語。因" +"此,您可能需要執行以下項目:" + +#: src/chromium/adding-third-party-crates/keeping-up-to-date.md +msgid "" +"As the OWNER of any third party Chromium dependency, you are [expected to " +"keep it up to date with any security fixes](https://chromium.googlesource." +"com/chromium/src/+/main/docs/adding_to_third_party.md#add-owners). It is " +"hoped that we will soon automate this for Rust crates, but for now, it's " +"still your responsibility just as it is for any other third party dependency." +msgstr "" +"身為第三方 Chromium 依附元件的擁有者,您應[確保該元件已採用任何最新的安全性修" +"正項目](https://chromium.googlesource.com/chromium/src/+/main/docs/" +"adding_to_third_party.md#add-owners)。我們希望很快就能針對 Rust Crate 將這項" +"作業自動化,但您目前仍須負責處理此事,如同使用其他第三方依附元件時一樣。" + +#: src/exercises/chromium/third-party.md +msgid "" +"Add [uwuify](https://crates.io/crates/uwuify) to Chromium, turning off the " +"crate's [default features](https://doc.rust-lang.org/cargo/reference/" +"features.html#the-default-feature). Assume that the crate will be used in " +"shipping Chromium, but won't be used to handle untrustworthy input." +msgstr "" +"在 Chromium 中新增 [uwuify](https://crates.io/crates/uwuify),關閉 Crate 的" +"[預設功能](https://doc.rust-lang.org/cargo/reference/features.html#the-" +"default-feature)。假設提交 Chromium 時會使用這個 Crate,但不會用於處理不可靠" +"的輸入資料。" + +#: src/exercises/chromium/third-party.md +msgid "" +"(In the next exercise we'll use uwuify from Chromium, but feel free to skip " +"ahead and do that now if you like. Or, you could create a new " +"[`rust_executable` target](https://source.chromium.org/chromium/chromium/src/" +"+/main:build/rust/rust_executable.gni) which uses `uwuify`)." +msgstr "" +"(在下一項練習中,我們將使用 Chromium 的 uwuify,但您現在就可以跳過這部分,直" +"接開始練習。或者,您可以建立使用 `uwuify` 的新 [`rust_executable` 目標]" +"(https://source.chromium.org/chromium/chromium/src/+/main:build/rust/" +"rust_executable.gni)。)" + +#: src/exercises/chromium/third-party.md +msgid "Students will need to download lots of transitive dependencies." +msgstr "學生需下載許多遞移依附元件。" + +#: src/exercises/chromium/third-party.md +msgid "The total crates needed are:" +msgstr "以下為所有需要的 Crate:" + +#: src/exercises/chromium/third-party.md +msgid "`instant`," +msgstr "`instant`," + +#: src/exercises/chromium/third-party.md +msgid "`lock_api`," +msgstr "`lock_api`," + +#: src/exercises/chromium/third-party.md +msgid "`parking_lot`," +msgstr "`parking_lot`," + +#: src/exercises/chromium/third-party.md +msgid "`parking_lot_core`," +msgstr "`parking_lot_core`," + +#: src/exercises/chromium/third-party.md +msgid "`redox_syscall`," +msgstr "`redox_syscall`," + +#: src/exercises/chromium/third-party.md +msgid "`scopeguard`," +msgstr "`scopeguard`," + +#: src/exercises/chromium/third-party.md +msgid "`smallvec`, and" +msgstr "`smallvec`,以及" + +#: src/exercises/chromium/third-party.md +msgid "`uwuify`." +msgstr "`uwuify`。" + +#: src/exercises/chromium/third-party.md +msgid "" +"If students are downloading even more than that, they probably forgot to " +"turn off the default features." +msgstr "如果學生下載的項目不只這些,可能是因為忘了關閉預設功能。" + +#: src/exercises/chromium/third-party.md +msgid "" +"Thanks to [Daniel Liu](https://github.com/Daniel-Liu-c0deb0t) for this crate!" +msgstr "" +"感謝 [Daniel Liu](https://github.com/Daniel-Liu-c0deb0t) 提供這個 Crate!" + +#: src/exercises/chromium/bringing-it-together.md +msgid "Bringing It Together --- Exercise" +msgstr "融會貫通 - 練習" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"In this exercise, you're going to add a whole new Chromium feature, bringing " +"together everything you already learned." +msgstr "在本練習中,您會加入全新的 Chromium 功能,一併應用目前學到的所有內容。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "The Brief from Product Management" +msgstr "產品管理提要" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"A community of pixies has been discovered living in a remote rainforest. " +"It's important that we get Chromium for Pixies delivered to them as soon as " +"possible." +msgstr "" +"我們在偏遠的雨林中發現一群精靈,務必盡快將精靈專用 Chromium 提供給他們。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"The requirement is to translate all Chromium's UI strings into Pixie " +"language." +msgstr "目前要求是將所有 Chromium 的 UI 字串翻譯成精靈語。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"There's not time to wait for proper translations, but fortunately pixie " +"language is very close to English, and it turns out there's a Rust crate " +"which does the translation." +msgstr "" +"現在沒時間取得適當的翻譯,但幸好精靈語非常接近英文,也找到能負責翻譯的 Rust " +"Crate。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"In fact, you already [imported that crate in the previous exercise](https://" +"crates.io/crates/uwuify)." +msgstr "" +"其實,您已經[在先前的練習中匯入這個 Crate](https://crates.io/crates/uwuify)。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"(Obviously, real translations of Chrome require incredible care and " +"diligence. Don't ship this!)" +msgstr "(想當然耳,實際翻譯 Chrome 時必須非常審慎認真。千萬別發布這些內容!)" + +#: src/exercises/chromium/bringing-it-together.md +msgid "Steps" +msgstr "步驟" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"Modify `ResourceBundle::MaybeMangleLocalizedString` so that it uwuifies all " +"strings before display. In this special build of Chromium, it should always " +"do this irrespective of the setting of `mangle_localized_strings_`." +msgstr "" +"修改 `ResourceBundle::MaybeMangleLocalizedString`,讓所有字串在顯示前 uwu " +"化。在這個特殊版本的 Chromium 中,無論 `mangle_localized_strings_` 的設定為" +"何,一律應執行這項轉換。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"If you've done everything right across all these exercises, congratulations, " +"you should have created Chrome for pixies!" +msgstr "如果您順利完成所有練習,那麼恭喜您成功為精靈打造了 Chrome!" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"UTF16 vs UTF8. Students should be aware that Rust strings are always UTF8, " +"and will probably decide that it's better to do the conversion on the C++ " +"side using `base::UTF16ToUTF8` and back again." +msgstr "" +"UTF16 與 UTF8:學生應瞭解 Rust 字串一律為 UTF8,且可能判斷出較適合在 C++ 端使" +"用 `base::UTF16ToUTF8` 完成轉換再返回。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"If students decide to do the conversion on the Rust side, they'll need to " +"consider [`String::from_utf16`](https://doc.rust-lang.org/std/string/struct." +"String.html#method.from_utf16), consider error handling, and consider which " +"[CXX supported types can transfer a lot of u16s](https://cxx.rs/binding/" +"slice.html)." +msgstr "" +"如果學生決定在 Rust 端完成轉換,就需考慮 [`String::from_utf16`](https://doc." +"rust-lang.org/std/string/struct.String.html#method.from_utf16)、錯誤處理方" +"式,以及哪些 [CXX 支援的型別可傳輸大量 u16](https://cxx.rs/binding/slice." +"html)。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"Students may design the C++/Rust boundary in several different ways, e.g. " +"taking and returning strings by value, or taking a mutable reference to a " +"string. If a mutable reference is used, CXX will likely tell the student " +"that they need to use [`Pin`](https://doc.rust-lang.org/std/pin/). You may " +"need to explain what `Pin` does, and then explain why CXX needs it for " +"mutable references to C++ data: the answer is that C++ data can't be moved " +"around like Rust data, because it may contain self-referential pointers." +msgstr "" +"學生可透過多種不同的方式設計 C++/Rust 界線,例如依值擷取及傳回字串,或是對字" +"串採用可變動參照。如果使用可變動參照,CXX 可能會告知學生需使用 [`Pin`]" +"(https://doc.rust-lang.org/std/pin/)。您可能需要說明 `Pin` 的功用,並解釋為" +"何 CXX 需要它來處理 C++ 資料的可變動參照:答案是 C++ 資料無法像 Rust 資料一樣" +"移動,因為該資料可能包含自我參照指標。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"The C++ target containing `ResourceBundle::MaybeMangleLocalizedString` will " +"need to depend on a `rust_static_library` target. The student probably " +"already did this." +msgstr "" +"包含 `ResourceBundle::MaybeMangleLocalizedString` 的 C++ 目標需依附於 " +"`rust_static_library` 目標。學生可能已經這麼做。" + +#: src/exercises/chromium/bringing-it-together.md +msgid "" +"The `rust_static_library` target will need to depend on `//third_party/rust/" +"uwuify/v0_2:lib`." +msgstr "" +"`rust_static_library` 目標需依附於 `//third_party/rust/uwuify/v0_2:lib`。" + +#: src/exercises/chromium/solutions.md +msgid "" +"Solutions to the Chromium exercises can be found in [this series of CLs]" +"(https://chromium-review.googlesource.com/c/chromium/src/+/5096560)." +msgstr "" +"如需 Chromium 練習的解決方案,請參閱[這個 CL 系列](https://chromium-review." +"googlesource.com/c/chromium/src/+/5096560)。" + +#: src/bare-metal.md +msgid "Welcome to Bare Metal Rust" +msgstr "歡迎瞭解 Rust 裸機開發" + +#: src/bare-metal.md msgid "" "This is a standalone one-day course about bare-metal Rust, aimed at people " "who are familiar with the basics of Rust (perhaps from completing the " "Comprehensive Rust course), and ideally also have some experience with bare-" "metal programming in some other language such as C." msgstr "" +"這個為期一天的獨立課程會介紹 Rust 裸機開發,適合熟悉 Rust 基本概念的開發人員 " +"(或許是完成 Comprehensive Rust 課程的學生),且最好具備一些 C 等其他語言的裸機" +"程式設計經驗。" -#: src/bare-metal.md:7 +#: src/bare-metal.md msgid "" "Today we will talk about 'bare-metal' Rust: running Rust code without an OS " "underneath us. This will be divided into several parts:" msgstr "" +"今天我們要介紹 Rust「裸機開發」:在執行 Rust 程式碼時不使用作業系統。這會分為" +"以下幾個部分:" -#: src/bare-metal.md:10 +#: src/bare-metal.md msgid "What is `no_std` Rust?" -msgstr "" +msgstr "什麼是 `no_std` Rust?" -#: src/bare-metal.md:11 +#: src/bare-metal.md msgid "Writing firmware for microcontrollers." -msgstr "" +msgstr "編寫微控制器的韌體。" -#: src/bare-metal.md:12 +#: src/bare-metal.md msgid "Writing bootloader / kernel code for application processors." -msgstr "" +msgstr "編寫應用程式處理器的系統啟動載入程式/核心程式碼。" -#: src/bare-metal.md:13 +#: src/bare-metal.md msgid "Some useful crates for bare-metal Rust development." -msgstr "" +msgstr "一些適用於 Rust 裸機開發的實用 Crate。" -#: src/bare-metal.md:15 +#: src/bare-metal.md msgid "" "For the microcontroller part of the course we will use the [BBC micro:bit]" "(https://microbit.org/) v2 as an example. It's a [development board](https://" @@ -13466,671 +16801,436 @@ msgid "" "with some LEDs and buttons, an I2C-connected accelerometer and compass, and " "an on-board SWD debugger." msgstr "" +"在本課程的微控制器部分,我們將使用 [BBC micro:bit](https://microbit.org/) 第 " +"2 版當做範例。這是以 Nordic nRF51822 微控制器為基礎的[開發板](https://tech." +"microbit.org/hardware/),具備一些 LED 和按鈕、連接 I2C 的加速計和羅盤,以及內" +"建的 SWD 偵錯工具。" -#: src/bare-metal.md:20 +#: src/bare-metal.md msgid "" "To get started, install some tools we'll need later. On gLinux or Debian:" -msgstr "" +msgstr "如要開始使用,請先安裝稍後需使用的工具。使用 gLinux 或 Debian:" -#: src/bare-metal.md:22 -msgid "" -"```bash\n" -"sudo apt install gcc-aarch64-linux-gnu gdb-multiarch libudev-dev picocom pkg-" -"config qemu-system-arm\n" -"rustup update\n" -"rustup target add aarch64-unknown-none thumbv7em-none-eabihf\n" -"rustup component add llvm-tools-preview\n" -"cargo install cargo-binutils cargo-embed\n" -"```" -msgstr "" - -#: src/bare-metal.md:30 +#: src/bare-metal.md msgid "" "And give users in the `plugdev` group access to the micro:bit programmer:" -msgstr "" +msgstr "為 `plugdev` 群組中的使用者授予 micro:bit 程式工具的存取權:" -#: src/bare-metal.md:32 -msgid "" -"```bash\n" -"echo 'SUBSYSTEM==\"usb\", ATTR{idVendor}==\"0d28\", MODE=\"0664\", " -"GROUP=\"plugdev\"' |\\\n" -" sudo tee /etc/udev/rules.d/50-microbit.rules\n" -"sudo udevadm control --reload-rules\n" -"```" -msgstr "" - -#: src/bare-metal.md:38 +#: src/bare-metal.md src/bare-metal/microcontrollers/debugging.md msgid "On MacOS:" -msgstr "" +msgstr "使用 MacOS:" -#: src/bare-metal.md:40 -msgid "" -"```bash\n" -"xcode-select --install\n" -"brew install gdb picocom qemu\n" -"brew install --cask gcc-aarch64-embedded\n" -"rustup update\n" -"rustup target add aarch64-unknown-none thumbv7em-none-eabihf\n" -"rustup component add llvm-tools-preview\n" -"cargo install cargo-binutils cargo-embed\n" -"```" -msgstr "" - -#: src/bare-metal/no_std.md:1 -msgid "`no_std`" -msgstr "" - -#: src/bare-metal/no_std.md:7 +#: src/bare-metal/no_std.md msgid "`core`" -msgstr "" +msgstr "`core`" -#: src/bare-metal/no_std.md:12 src/bare-metal/alloc.md:1 -msgid "`alloc`" -msgstr "" - -#: src/bare-metal/no_std.md:17 +#: src/bare-metal/no_std.md msgid "`std`" -msgstr "" +msgstr "`std`" -#: src/bare-metal/no_std.md:24 +#: src/bare-metal/no_std.md msgid "Slices, `&str`, `CStr`" -msgstr "" +msgstr "切片、`&str`、`CStr`" -#: src/bare-metal/no_std.md:25 +#: src/bare-metal/no_std.md msgid "`NonZeroU8`..." -msgstr "" +msgstr "`NonZeroU8`..." -#: src/bare-metal/no_std.md:26 +#: src/bare-metal/no_std.md msgid "`Option`, `Result`" -msgstr "" +msgstr "`Option`、`Result`" -#: src/bare-metal/no_std.md:27 +#: src/bare-metal/no_std.md msgid "`Display`, `Debug`, `write!`..." -msgstr "" +msgstr "`Display`、`Debug`、`write!`..." -#: src/bare-metal/no_std.md:29 +#: src/bare-metal/no_std.md msgid "`panic!`, `assert_eq!`..." -msgstr "" +msgstr "`panic!`、`assert_eq!`..." -#: src/bare-metal/no_std.md:30 +#: src/bare-metal/no_std.md msgid "`NonNull` and all the usual pointer-related functions" -msgstr "" +msgstr "`NonNull` 和所有一般指標相關函式" -#: src/bare-metal/no_std.md:31 +#: src/bare-metal/no_std.md msgid "`Future` and `async`/`await`" -msgstr "" +msgstr "`Future` 和 `async`/`await`" -#: src/bare-metal/no_std.md:32 +#: src/bare-metal/no_std.md msgid "`fence`, `AtomicBool`, `AtomicPtr`, `AtomicU32`..." -msgstr "" +msgstr "`fence`、`AtomicBool`、`AtomicPtr`、`AtomicU32`..." -#: src/bare-metal/no_std.md:33 +#: src/bare-metal/no_std.md msgid "`Duration`" -msgstr "" +msgstr "`Duration`" -#: src/bare-metal/no_std.md:38 +#: src/bare-metal/no_std.md msgid "`Box`, `Cow`, `Arc`, `Rc`" -msgstr "" +msgstr "`Box`、`Cow`、`Arc`、`Rc`" -#: src/bare-metal/no_std.md:39 +#: src/bare-metal/no_std.md msgid "`Vec`, `BinaryHeap`, `BtreeMap`, `LinkedList`, `VecDeque`" -msgstr "" +msgstr "`Vec`、`BinaryHeap`、`BtreeMap`、`LinkedList`、`VecDeque`" -#: src/bare-metal/no_std.md:40 +#: src/bare-metal/no_std.md msgid "`String`, `CString`, `format!`" -msgstr "" +msgstr "`String`、`CString`、`format!`" -#: src/bare-metal/no_std.md:45 +#: src/bare-metal/no_std.md msgid "`Error`" -msgstr "" +msgstr "`Error`" -#: src/bare-metal/no_std.md:47 +#: src/bare-metal/no_std.md msgid "`Mutex`, `Condvar`, `Barrier`, `Once`, `RwLock`, `mpsc`" -msgstr "" +msgstr "`Mutex`、`Condvar`、`Barrier`、`Once`、`RwLock`、`mpsc`" -#: src/bare-metal/no_std.md:48 +#: src/bare-metal/no_std.md msgid "`File` and the rest of `fs`" -msgstr "" +msgstr "`File` 和 `fs` 其餘部分" -#: src/bare-metal/no_std.md:49 +#: src/bare-metal/no_std.md msgid "`println!`, `Read`, `Write`, `Stdin`, `Stdout` and the rest of `io`" -msgstr "" +msgstr "`println!`、`Read`、`Write`、`Stdin`、`Stdout` 和 `io` 其餘部分" -#: src/bare-metal/no_std.md:50 +#: src/bare-metal/no_std.md msgid "`Path`, `OsString`" -msgstr "" +msgstr "`Path`、`OsString`" -#: src/bare-metal/no_std.md:51 +#: src/bare-metal/no_std.md msgid "`net`" -msgstr "" +msgstr "`net`" -#: src/bare-metal/no_std.md:52 +#: src/bare-metal/no_std.md msgid "`Command`, `Child`, `ExitCode`" -msgstr "" +msgstr "`Command`、`Child`、`ExitCode`" -#: src/bare-metal/no_std.md:53 +#: src/bare-metal/no_std.md msgid "`spawn`, `sleep` and the rest of `thread`" -msgstr "" +msgstr "`spawn`、`sleep` 和 `thread` 其餘部分" -#: src/bare-metal/no_std.md:54 +#: src/bare-metal/no_std.md msgid "`SystemTime`, `Instant`" -msgstr "" +msgstr "`SystemTime`、`Instant`" -#: src/bare-metal/no_std.md:62 +#: src/bare-metal/no_std.md msgid "`HashMap` depends on RNG." -msgstr "" +msgstr "`HashMap` 依附於 RNG。" -#: src/bare-metal/no_std.md:63 +#: src/bare-metal/no_std.md msgid "`std` re-exports the contents of both `core` and `alloc`." -msgstr "" +msgstr "`std` 會重新匯出 `core` 和 `alloc` 的內容。" -#: src/bare-metal/minimal.md:1 +#: src/bare-metal/minimal.md msgid "A minimal `no_std` program" -msgstr "" +msgstr "最簡單的 `no_std` 程式" -#: src/bare-metal/minimal.md:3 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"use core::panic::PanicInfo;\n" -"\n" -"#[panic_handler]\n" -"fn panic(_panic: &PanicInfo) -> ! {\n" -" loop {}\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/minimal.md:17 +#: src/bare-metal/minimal.md msgid "This will compile to an empty binary." -msgstr "" +msgstr "這會編譯為空白的二進位檔。" -#: src/bare-metal/minimal.md:18 +#: src/bare-metal/minimal.md msgid "`std` provides a panic handler; without it we must provide our own." -msgstr "" +msgstr "`std` 提供恐慌處理常式。如果沒有,我們就須自行提供。" -#: src/bare-metal/minimal.md:19 +#: src/bare-metal/minimal.md msgid "It can also be provided by another crate, such as `panic-halt`." -msgstr "" +msgstr "也可以由其他 Crate 提供,例如 `panic-halt`。" -#: src/bare-metal/minimal.md:20 +#: src/bare-metal/minimal.md msgid "" "Depending on the target, you may need to compile with `panic = \"abort\"` to " "avoid an error about `eh_personality`." msgstr "" +"視目標而定,編譯時可能需要使用 `panic = \"abort\"`,以免發生 " +"`eh_personality` 相關錯誤。" -#: src/bare-metal/minimal.md:22 +#: src/bare-metal/minimal.md msgid "" "Note that there is no `main` or any other entry point; it's up to you to " "define your own entry point. This will typically involve a linker script and " "some assembly code to set things up ready for Rust code to run." msgstr "" +"請注意,並沒有 `main` 或任何其他進入點。您可以自行定義進入點。這通常涉及連結" +"器指令碼和一些組語程式碼,以便準備好執行 Rust 程式碼。" -#: src/bare-metal/alloc.md:3 +#: src/bare-metal/alloc.md msgid "" "To use `alloc` you must implement a [global (heap) allocator](https://doc." "rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html)." msgstr "" +"如要使用 `alloc`,您必須實作[全域 (堆積) 分配器](https://doc.rust-lang.org/" +"stable/std/alloc/trait.GlobalAlloc.html)。" -#: src/bare-metal/alloc.md:6 +#: src/bare-metal/alloc.md msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate alloc;\n" -"extern crate panic_halt as _;\n" -"\n" -"use alloc::string::ToString;\n" -"use alloc::vec::Vec;\n" -"use buddy_system_allocator::LockedHeap;\n" -"\n" -"#[global_allocator]\n" -"static HEAP_ALLOCATOR: LockedHeap<32> = LockedHeap::<32>::new();\n" -"\n" -"static mut HEAP: [u8; 65536] = [0; 65536];\n" -"\n" -"pub fn entry() {\n" -" // Safe because `HEAP` is only used here and `entry` is only called " -"once.\n" -" unsafe {\n" -" // Give the allocator some memory to allocate.\n" -" HEAP_ALLOCATOR\n" -" .lock()\n" -" .init(HEAP.as_mut_ptr() as usize, HEAP.len());\n" -" }\n" -"\n" -" // Now we can do things that require heap allocation.\n" -" let mut v = Vec::new();\n" -" v.push(\"A string\".to_string());\n" -"}\n" -"```" +"// Safe because `HEAP` is only used here and `entry` is only called once.\n" msgstr "" +"// Safe because `HEAP` is only used here and `entry` is only called once.\n" -#: src/bare-metal/alloc.md:39 +#: src/bare-metal/alloc.md +msgid "// Give the allocator some memory to allocate.\n" +msgstr "// Give the allocator some memory to allocate.\n" + +#: src/bare-metal/alloc.md +msgid "// Now we can do things that require heap allocation.\n" +msgstr "// Now we can do things that require heap allocation.\n" + +#: src/bare-metal/alloc.md +#, fuzzy +msgid "\"A string\"" +msgstr "String" + +#: src/bare-metal/alloc.md msgid "" "`buddy_system_allocator` is a third-party crate implementing a basic buddy " "system allocator. Other crates are available, or you can write your own or " "hook into your existing allocator." msgstr "" +"`buddy_system_allocator` 是實作基本夥伴系統分配器的第三方 Crate。也可以使用其" +"他 Crate,或是自行撰寫或連結至現有分配器。" -#: src/bare-metal/alloc.md:41 +#: src/bare-metal/alloc.md msgid "" "The const parameter of `LockedHeap` is the max order of the allocator; i.e. " "in this case it can allocate regions of up to 2\\*\\*32 bytes." msgstr "" +"`LockedHeap` 的 const 參數是分配器最高的階,意即在本例中,它最多可分配 " +"2\\*\\*32 個位元組的區域。" -#: src/bare-metal/alloc.md:43 +#: src/bare-metal/alloc.md msgid "" "If any crate in your dependency tree depends on `alloc` then you must have " "exactly one global allocator defined in your binary. Usually this is done in " "the top-level binary crate." msgstr "" +"如果依附元件樹狀結構中有任何 Crate 依附於 `alloc`,您就必須在二進位檔中只定義" +"一個全域分配器。通常是在頂層二進位檔 Crate 中定義。" -#: src/bare-metal/alloc.md:45 +#: src/bare-metal/alloc.md msgid "" "`extern crate panic_halt as _` is necessary to ensure that the `panic_halt` " "crate is linked in so we get its panic handler." msgstr "" +"務必使用 `extern crate panic_halt as _`,確保 `panic_halt` Crate 已連結,讓我" +"們能取得其恐慌處理常式。" -#: src/bare-metal/alloc.md:47 +#: src/bare-metal/alloc.md msgid "This example will build but not run, as it doesn't have an entry point." -msgstr "" +msgstr "這個範例將建構但不執行,因為沒有進入點。" -#: src/bare-metal/microcontrollers.md:3 +#: src/bare-metal/microcontrollers.md msgid "" "The `cortex_m_rt` crate provides (among other things) a reset handler for " "Cortex M microcontrollers." msgstr "" +"`cortex_m_rt` Crate 提供 Cortex M 微控制器的重設處理常式 (和其他項目)。" -#: src/bare-metal/microcontrollers.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"mod interrupts;\n" -"\n" -"use cortex_m_rt::entry;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" loop {}\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers.md:21 +#: src/bare-metal/microcontrollers.md msgid "" "Next we'll look at how to access peripherals, with increasing levels of " "abstraction." -msgstr "" +msgstr "接下來,我們要探討如何存取周邊裝置,會有愈來愈多層的抽象化。" -#: src/bare-metal/microcontrollers.md:25 +#: src/bare-metal/microcontrollers.md msgid "" "The `cortex_m_rt::entry` macro requires that the function have type `fn() -" "> !`, because returning to the reset handler doesn't make sense." msgstr "" +"`cortex_m_rt::entry` 巨集規定函式必須具有 `fn() -> !` 型別,因為返回重設處理" +"常式並不合理。" -#: src/bare-metal/microcontrollers.md:27 +#: src/bare-metal/microcontrollers.md msgid "Run the example with `cargo embed --bin minimal`" -msgstr "" +msgstr "使用 `cargo embed --bin minimal` 執行範例" -#: src/bare-metal/microcontrollers/mmio.md:3 +#: src/bare-metal/microcontrollers/mmio.md msgid "" "Most microcontrollers access peripherals via memory-mapped IO. Let's try " "turning on an LED on our micro:bit:" msgstr "" +"大多數微控制器會透過記憶體對映 IO 存取周邊裝置。請嘗試在 micro:bit 上開啟 " +"LED:" -#: src/bare-metal/microcontrollers/mmio.md:6 +#: src/bare-metal/microcontrollers/mmio.md +msgid "/// GPIO port 0 peripheral address\n" +msgstr "/// GPIO port 0 peripheral address\n" + +#: src/bare-metal/microcontrollers/mmio.md +msgid "// GPIO peripheral offsets\n" +msgstr "// GPIO peripheral offsets\n" + +#: src/bare-metal/microcontrollers/mmio.md +msgid "// PIN_CNF fields\n" +msgstr "// PIN_CNF fields\n" + +#: src/bare-metal/microcontrollers/mmio.md +#: src/bare-metal/microcontrollers/pacs.md +#: src/bare-metal/microcontrollers/hals.md +msgid "// Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" +msgstr "// Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" + +#: src/bare-metal/microcontrollers/mmio.md msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"mod interrupts;\n" -"\n" -"use core::mem::size_of;\n" -"use cortex_m_rt::entry;\n" -"\n" -"/// GPIO port 0 peripheral address\n" -"const GPIO_P0: usize = 0x5000_0000;\n" -"\n" -"// GPIO peripheral offsets\n" -"const PIN_CNF: usize = 0x700;\n" -"const OUTSET: usize = 0x508;\n" -"const OUTCLR: usize = 0x50c;\n" -"\n" -"// PIN_CNF fields\n" -"const DIR_OUTPUT: u32 = 0x1;\n" -"const INPUT_DISCONNECT: u32 = 0x1 << 1;\n" -"const PULL_DISABLED: u32 = 0x0 << 2;\n" -"const DRIVE_S0S1: u32 = 0x0 << 8;\n" -"const SENSE_DISABLED: u32 = 0x0 << 16;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" -" let pin_cnf_21 = (GPIO_P0 + PIN_CNF + 21 * size_of::()) as *mut " -"u32;\n" -" let pin_cnf_28 = (GPIO_P0 + PIN_CNF + 28 * size_of::()) as *mut " -"u32;\n" -" // Safe because the pointers are to valid peripheral control registers, " -"and\n" +"// Safe because the pointers are to valid peripheral control registers, and\n" " // no aliases exist.\n" -" unsafe {\n" -" pin_cnf_21.write_volatile(\n" -" DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | " -"SENSE_DISABLED,\n" -" );\n" -" pin_cnf_28.write_volatile(\n" -" DIR_OUTPUT | INPUT_DISCONNECT | PULL_DISABLED | DRIVE_S0S1 | " -"SENSE_DISABLED,\n" -" );\n" -" }\n" -"\n" -" // Set pin 28 low and pin 21 high to turn the LED on.\n" -" let gpio0_outset = (GPIO_P0 + OUTSET) as *mut u32;\n" -" let gpio0_outclr = (GPIO_P0 + OUTCLR) as *mut u32;\n" -" // Safe because the pointers are to valid peripheral control registers, " -"and\n" -" // no aliases exist.\n" -" unsafe {\n" -" gpio0_outclr.write_volatile(1 << 28);\n" -" gpio0_outset.write_volatile(1 << 21);\n" -" }\n" -"\n" -" loop {}\n" -"}\n" -"```" msgstr "" +"// Safe because the pointers are to valid peripheral control registers, and\n" +" // no aliases exist.\n" -#: src/bare-metal/microcontrollers/mmio.md:64 +#: src/bare-metal/microcontrollers/mmio.md +#: src/bare-metal/microcontrollers/pacs.md +#: src/bare-metal/microcontrollers/hals.md +msgid "// Set pin 28 low and pin 21 high to turn the LED on.\n" +msgstr "// Set pin 28 low and pin 21 high to turn the LED on.\n" + +#: src/bare-metal/microcontrollers/mmio.md msgid "" "GPIO 0 pin 21 is connected to the first column of the LED matrix, and pin 28 " "to the first row." -msgstr "" +msgstr "GPIO 0 接腳 21 連接至 LED 矩陣的第一欄,接腳 28 則連接至第一列。" -#: src/bare-metal/microcontrollers/mmio.md:66 -#: src/bare-metal/microcontrollers/pacs.md:59 -#: src/bare-metal/microcontrollers/hals.md:43 -#: src/bare-metal/microcontrollers/board-support.md:34 +#: src/bare-metal/microcontrollers/mmio.md +#: src/bare-metal/microcontrollers/pacs.md +#: src/bare-metal/microcontrollers/hals.md +#: src/bare-metal/microcontrollers/board-support.md msgid "Run the example with:" -msgstr "" +msgstr "使用下列指令執行範例:" -#: src/bare-metal/microcontrollers/mmio.md:68 -msgid "" -"```sh\n" -"cargo embed --bin mmio\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/pacs.md:1 +#: src/bare-metal/microcontrollers/pacs.md msgid "Peripheral Access Crates" -msgstr "" +msgstr "周邊裝置存取 Crate" -#: src/bare-metal/microcontrollers/pacs.md:3 +#: src/bare-metal/microcontrollers/pacs.md msgid "" "[`svd2rust`](https://crates.io/crates/svd2rust) generates mostly-safe Rust " "wrappers for memory-mapped peripherals from [CMSIS-SVD](https://www.keil.com/" "pack/doc/CMSIS/SVD/html/index.html) files." msgstr "" +"[`svd2rust`](https://crates.io/crates/svd2rust) 會針對 [CMSIS-SVD](https://" +"www.keil.com/pack/doc/CMSIS/SVD/html/index.html) 檔案中記憶體對映周邊裝置,產" +"生大多是安全的 Rust 包裝函式。" -#: src/bare-metal/microcontrollers/pacs.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use cortex_m_rt::entry;\n" -"use nrf52833_pac::Peripherals;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let p = Peripherals::take().unwrap();\n" -" let gpio0 = p.P0;\n" -"\n" -" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" -" gpio0.pin_cnf[21].write(|w| {\n" -" w.dir().output();\n" -" w.input().disconnect();\n" -" w.pull().disabled();\n" -" w.drive().s0s1();\n" -" w.sense().disabled();\n" -" w\n" -" });\n" -" gpio0.pin_cnf[28].write(|w| {\n" -" w.dir().output();\n" -" w.input().disconnect();\n" -" w.pull().disabled();\n" -" w.drive().s0s1();\n" -" w.sense().disabled();\n" -" w\n" -" });\n" -"\n" -" // Set pin 28 low and pin 21 high to turn the LED on.\n" -" gpio0.outclr.write(|w| w.pin28().clear());\n" -" gpio0.outset.write(|w| w.pin21().set());\n" -"\n" -" loop {}\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/pacs.md:49 +#: src/bare-metal/microcontrollers/pacs.md msgid "" "SVD (System View Description) files are XML files typically provided by " "silicon vendors which describe the memory map of the device." msgstr "" +"SVD (系統視圖說明) 檔案通常是晶片供應商提供的 XML 檔案,描述裝置的記憶體對" +"映。" -#: src/bare-metal/microcontrollers/pacs.md:51 +#: src/bare-metal/microcontrollers/pacs.md msgid "" "They are organised by peripheral, register, field and value, with names, " "descriptions, addresses and so on." msgstr "" +"這種檔案的分類依據為周邊裝置、暫存器、欄位和值,具有名稱、說明、位址等資訊。" -#: src/bare-metal/microcontrollers/pacs.md:53 +#: src/bare-metal/microcontrollers/pacs.md msgid "" "SVD files are often buggy and incomplete, so there are various projects " "which patch the mistakes, add missing details, and publish the generated " "crates." msgstr "" +"SVD 檔案通常有很多錯誤且不完整,因此會使用各種專案修補錯誤、新增缺少的詳細資" +"料,以及發布產生的 Crate。" -#: src/bare-metal/microcontrollers/pacs.md:55 +#: src/bare-metal/microcontrollers/pacs.md msgid "`cortex-m-rt` provides the vector table, among other things." -msgstr "" +msgstr "`cortex-m-rt` 提供向量表等內容。" -#: src/bare-metal/microcontrollers/pacs.md:56 +#: src/bare-metal/microcontrollers/pacs.md msgid "" "If you `cargo install cargo-binutils` then you can run `cargo objdump --bin " "pac -- -d --no-show-raw-insn` to see the resulting binary." msgstr "" +"如果使用 `cargo install cargo-binutils`,則可以執行 `cargo objdump --bin pac " +"-- -d --no-show-raw-insn`,查看產生的二進位檔。" -#: src/bare-metal/microcontrollers/pacs.md:61 -msgid "" -"```sh\n" -"cargo embed --bin pac\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/hals.md:1 +#: src/bare-metal/microcontrollers/hals.md msgid "HAL crates" -msgstr "" +msgstr "HAL Crate" -#: src/bare-metal/microcontrollers/hals.md:3 +#: src/bare-metal/microcontrollers/hals.md msgid "" "[HAL crates](https://github.com/rust-embedded/awesome-embedded-rust#hal-" "implementation-crates) for many microcontrollers provide wrappers around " "various peripherals. These generally implement traits from [`embedded-hal`]" "(https://crates.io/crates/embedded-hal)." msgstr "" +"許多微控制器的 [HAL Crate](https://github.com/rust-embedded/awesome-embedded-" +"rust#hal-implementation-crates) 能為各種周邊裝置提供包裝函式。這些項目通常會" +"實作 [`embedded-hal`](https://crates.io/crates/embedded-hal) 的特徵。" -#: src/bare-metal/microcontrollers/hals.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use cortex_m_rt::entry;\n" -"use nrf52833_hal::gpio::{p0, Level};\n" -"use nrf52833_hal::pac::Peripherals;\n" -"use nrf52833_hal::prelude::*;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let p = Peripherals::take().unwrap();\n" -"\n" -" // Create HAL wrapper for GPIO port 0.\n" -" let gpio0 = p0::Parts::new(p.P0);\n" -"\n" -" // Configure GPIO 0 pins 21 and 28 as push-pull outputs.\n" -" let mut col1 = gpio0.p0_28.into_push_pull_output(Level::High);\n" -" let mut row1 = gpio0.p0_21.into_push_pull_output(Level::Low);\n" -"\n" -" // Set pin 28 low and pin 21 high to turn the LED on.\n" -" col1.set_low().unwrap();\n" -" row1.set_high().unwrap();\n" -"\n" -" loop {}\n" -"}\n" -"```" -msgstr "" +#: src/bare-metal/microcontrollers/hals.md +msgid "// Create HAL wrapper for GPIO port 0.\n" +msgstr "// Create HAL wrapper for GPIO port 0.\n" -#: src/bare-metal/microcontrollers/hals.md:39 +#: src/bare-metal/microcontrollers/hals.md msgid "" "`set_low` and `set_high` are methods on the `embedded_hal` `OutputPin` trait." -msgstr "" +msgstr "`set_low` 和 `set_high` 是 `embedded_hal` `OutputPin` 特徵上的方法。" -#: src/bare-metal/microcontrollers/hals.md:40 +#: src/bare-metal/microcontrollers/hals.md msgid "" "HAL crates exist for many Cortex-M and RISC-V devices, including various " "STM32, GD32, nRF, NXP, MSP430, AVR and PIC microcontrollers." msgstr "" +"許多 Cortex-M 和 RISC-V 裝置都有 HAL Crate,包括各種 STM32、GD32、nRF、NXP、" +"MSP430、AVR 和 PIC 微控制器。" -#: src/bare-metal/microcontrollers/hals.md:45 -msgid "" -"```sh\n" -"cargo embed --bin hal\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/board-support.md:1 +#: src/bare-metal/microcontrollers/board-support.md msgid "Board support crates" -msgstr "" +msgstr "開發板支援 Crate" -#: src/bare-metal/microcontrollers/board-support.md:3 +#: src/bare-metal/microcontrollers/board-support.md msgid "" "Board support crates provide a further level of wrapping for a specific " "board for convenience." -msgstr "" +msgstr "為方便起見,開發板支援 Crate 可針對特定開發板提供進一步包裝。" -#: src/bare-metal/microcontrollers/board-support.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use cortex_m_rt::entry;\n" -"use microbit::hal::prelude::*;\n" -"use microbit::Board;\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let mut board = Board::take().unwrap();\n" -"\n" -" board.display_pins.col1.set_low().unwrap();\n" -" board.display_pins.row1.set_high().unwrap();\n" -"\n" -" loop {}\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/board-support.md:28 +#: src/bare-metal/microcontrollers/board-support.md msgid "" "In this case the board support crate is just providing more useful names, " "and a bit of initialisation." -msgstr "" +msgstr "在本例中,開發板支援 Crate 只會提供更多實用名稱,以及一些初始化作業。" -#: src/bare-metal/microcontrollers/board-support.md:30 +#: src/bare-metal/microcontrollers/board-support.md msgid "" "The crate may also include drivers for some on-board devices outside of the " "microcontroller itself." -msgstr "" +msgstr "除了微控制器本身,Crate 或許也包含部分內建裝置的驅動程式。" -#: src/bare-metal/microcontrollers/board-support.md:32 +#: src/bare-metal/microcontrollers/board-support.md msgid "`microbit-v2` includes a simple driver for the LED matrix." -msgstr "" +msgstr "`microbit-v2` 包含 LED 矩陣的簡易驅動程式。" -#: src/bare-metal/microcontrollers/board-support.md:36 -msgid "" -"```sh\n" -"cargo embed --bin board_support\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/type-state.md:1 +#: src/bare-metal/microcontrollers/type-state.md msgid "The type state pattern" -msgstr "" +msgstr "型別狀態模式" -#: src/bare-metal/microcontrollers/type-state.md:3 -msgid "" -"```rust,editable,compile_fail\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let p = Peripherals::take().unwrap();\n" -" let gpio0 = p0::Parts::new(p.P0);\n" -"\n" -" let pin: P0_01 = gpio0.p0_01;\n" -"\n" -" // let gpio0_01_again = gpio0.p0_01; // Error, moved.\n" -" let pin_input: P0_01> = pin.into_floating_input();\n" -" if pin_input.is_high().unwrap() {\n" -" // ...\n" -" }\n" -" let mut pin_output: P0_01> = pin_input\n" -" .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, " -"Level::Low);\n" -" pin_output.set_high().unwrap();\n" -" // pin_input.is_high(); // Error, moved.\n" -"\n" -" let _pin2: P0_02> = gpio0\n" -" .p0_02\n" -" .into_open_drain_output(OpenDrainConfig::Disconnect0Standard1, " -"Level::Low);\n" -" let _pin3: P0_03> = gpio0.p0_03." -"into_push_pull_output(Level::Low);\n" -"\n" -" loop {}\n" -"}\n" -"```" -msgstr "" +#: src/bare-metal/microcontrollers/type-state.md +msgid "// let gpio0_01_again = gpio0.p0_01; // Error, moved.\n" +msgstr "// let gpio0_01_again = gpio0.p0_01; // Error, moved.\n" -#: src/bare-metal/microcontrollers/type-state.md:32 +#: src/bare-metal/microcontrollers/type-state.md +msgid "// pin_input.is_high(); // Error, moved.\n" +msgstr "// pin_input.is_high(); // Error, moved.\n" + +#: src/bare-metal/microcontrollers/type-state.md msgid "" "Pins don't implement `Copy` or `Clone`, so only one instance of each can " "exist. Once a pin is moved out of the port struct nobody else can take it." msgstr "" +"接腳不會實作 `Copy` 或 `Clone`,因此每個項目只能有一個實例。一旦接腳從連接埠" +"結構中移出,就無法再供使用。" -#: src/bare-metal/microcontrollers/type-state.md:34 +#: src/bare-metal/microcontrollers/type-state.md msgid "" "Changing the configuration of a pin consumes the old pin instance, so you " "can’t keep use the old instance afterwards." -msgstr "" +msgstr "變更接腳設定時會耗用舊的接腳例項,因此之後無法繼續使用舊的例項。" -#: src/bare-metal/microcontrollers/type-state.md:36 +#: src/bare-metal/microcontrollers/type-state.md msgid "" "The type of a value indicates the state that it is in: e.g. in this case, " "the configuration state of a GPIO pin. This encodes the state machine into " @@ -14138,594 +17238,791 @@ msgid "" "way without properly configuring it first. Illegal state transitions are " "caught at compile time." msgstr "" +"值的型別會指出其所處狀態,例如本例中 GPIO 接腳的設定狀態。這可將狀態機器編碼" +"至型別系統,確保您不會在未事先適當設定時嘗試使用接腳。在編譯期間,系統會偵測" +"非法的狀態轉換作業。" -#: src/bare-metal/microcontrollers/type-state.md:40 +#: src/bare-metal/microcontrollers/type-state.md msgid "" "You can call `is_high` on an input pin and `set_high` on an output pin, but " "not vice-versa." msgstr "" +"您可以對輸入接腳呼叫 `is_high`、對輸出接腳呼叫`set_high`,但不得反過來呼叫。" -#: src/bare-metal/microcontrollers/type-state.md:41 +#: src/bare-metal/microcontrollers/type-state.md msgid "Many HAL crates follow this pattern." -msgstr "" +msgstr "許多 HAL Crate 都遵循這個模式。" -#: src/bare-metal/microcontrollers/embedded-hal.md:1 -msgid "`embedded-hal`" -msgstr "" - -#: src/bare-metal/microcontrollers/embedded-hal.md:3 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "" "The [`embedded-hal`](https://crates.io/crates/embedded-hal) crate provides a " "number of traits covering common microcontroller peripherals." msgstr "" +"[`embedded-hal`](https://crates.io/crates/embedded-hal) Crate 提供多個特徵," +"涵蓋常見的微控制器周邊裝置。" -#: src/bare-metal/microcontrollers/embedded-hal.md:6 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "GPIO" -msgstr "" +msgstr "GPIO" -#: src/bare-metal/microcontrollers/embedded-hal.md:7 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "ADC" -msgstr "" +msgstr "ADC" -#: src/bare-metal/microcontrollers/embedded-hal.md:8 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "I2C, SPI, UART, CAN" -msgstr "" +msgstr "I2C、SPI、UART、CAN" -#: src/bare-metal/microcontrollers/embedded-hal.md:9 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "RNG" -msgstr "" +msgstr "RNG" -#: src/bare-metal/microcontrollers/embedded-hal.md:10 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "Timers" -msgstr "" +msgstr "計時器" -#: src/bare-metal/microcontrollers/embedded-hal.md:11 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "Watchdogs" -msgstr "" +msgstr "看門狗計時器" -#: src/bare-metal/microcontrollers/embedded-hal.md:13 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "" "Other crates then implement [drivers](https://github.com/rust-embedded/" "awesome-embedded-rust#driver-crates) in terms of these traits, e.g. an " "accelerometer driver might need an I2C or SPI bus implementation." msgstr "" +"其他 Crate 隨後會根據這些特徵實作[驅動程式](https://github.com/rust-embedded/" +"awesome-embedded-rust#driver-crates),例如加速計驅動程式可能需要實作 I2C 或 " +"SPI 匯流排。" -#: src/bare-metal/microcontrollers/embedded-hal.md:19 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "" "There are implementations for many microcontrollers, as well as other " "platforms such as Linux on Raspberry Pi." msgstr "" +"許多微控制器和其他平台 (例如 Raspberry Pi 上的 Linux) 都有相應的實作項目。" -#: src/bare-metal/microcontrollers/embedded-hal.md:21 +#: src/bare-metal/microcontrollers/embedded-hal.md msgid "" "There is work in progress on an `async` version of `embedded-hal`, but it " "isn't stable yet." -msgstr "" +msgstr "`embedded-hal` 的 `async` 版本已在開發中,但尚未推出穩定版。" -#: src/bare-metal/microcontrollers/probe-rs.md:1 -msgid "`probe-rs`, `cargo-embed`" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:3 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "[probe-rs](https://probe.rs/) is a handy toolset for embedded debugging, " "like OpenOCD but better integrated." msgstr "" +"[probe-rs](https://probe.rs/) 是適用於嵌入式偵錯的實用工具組,就像 OpenOCD," +"但整合效果更好。" -#: src/bare-metal/microcontrollers/probe-rs.md:6 -msgid "SWD" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:6 -msgid " and JTAG via CMSIS-DAP, ST-Link and J-Link probes" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:7 -msgid "GDB stub and Microsoft " -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:7 -msgid "DAP" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:7 -msgid " server" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:8 -msgid "Cargo integration" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:10 -msgid "`cargo-embed` is a cargo subcommand to build and flash binaries, log " -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:11 -msgid "RTT" -msgstr "" - -#: src/bare-metal/microcontrollers/probe-rs.md:11 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" -" output and connect GDB. It's configured by an `Embed.toml` file in your " -"project directory." -msgstr "" +"SWD (Serial Wire Debug) and JTAG via CMSIS-DAP, ST-Link and J-Link probes" +msgstr "透過 CMSIS-DAP、ST-Link 和 J-Link 探測器執行 SWD (序列線偵錯) 和 JTAG" -#: src/bare-metal/microcontrollers/probe-rs.md:16 +#: src/bare-metal/microcontrollers/probe-rs.md +msgid "GDB stub and Microsoft DAP (Debug Adapter Protocol) server" +msgstr "GDB 虛設常式和 Microsoft DAP (偵錯轉接程式通訊協定) 伺服器" + +#: src/bare-metal/microcontrollers/probe-rs.md +msgid "Cargo integration" +msgstr "Cargo 整合" + +#: src/bare-metal/microcontrollers/probe-rs.md +msgid "" +"`cargo-embed` is a cargo subcommand to build and flash binaries, log RTT " +"(Real Time Transfers) output and connect GDB. It's configured by an `Embed." +"toml` file in your project directory." +msgstr "" +"`cargo-embed` 是 Cargo 子指令,用於建構和刷新二進位檔、記錄 RTT (即時傳輸)輸" +"出內容,以及連結 GDB。這個指令是由專案目錄中的 `Embed.toml` 檔案來設定。" + +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "[CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) is " "an Arm standard protocol over USB for an in-circuit debugger to access the " "CoreSight Debug Access Port of various Arm Cortex processors. It's what the " "on-board debugger on the BBC micro:bit uses." msgstr "" +"[CMSIS-DAP](https://arm-software.github.io/CMSIS_5/DAP/html/index.html) 是針" +"對 USB 的 Arm 標準通訊協定,供電路內偵錯工具存取各種 Arm Cortex 處理器的 " +"CoreSight 偵錯存取埠。這就是 BBC micro:bit 內建偵錯工具所使用的通訊協定。" -#: src/bare-metal/microcontrollers/probe-rs.md:19 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "ST-Link is a range of in-circuit debuggers from ST Microelectronics, J-Link " "is a range from SEGGER." msgstr "" +"ST-Link 是 ST Microelectronics 推出的一系列電路內偵錯工具,J-Link 系列則來自 " +"SEGGER。" -#: src/bare-metal/microcontrollers/probe-rs.md:21 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "The Debug Access Port is usually either a 5-pin JTAG interface or 2-pin " "Serial Wire Debug." -msgstr "" +msgstr "偵錯存取埠通常是 5 接腳的 JTAG 介面或 2 接腳的序列線偵錯介面。" -#: src/bare-metal/microcontrollers/probe-rs.md:22 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "probe-rs is a library which you can integrate into your own tools if you " "want to." -msgstr "" +msgstr "您可以視需要將 probe-rs 程式庫整合至自己的工具。" -#: src/bare-metal/microcontrollers/probe-rs.md:23 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "The [Microsoft Debug Adapter Protocol](https://microsoft.github.io/debug-" "adapter-protocol/) lets VSCode and other IDEs debug code running on any " "supported microcontroller." msgstr "" +"[Microsoft 偵錯轉接程式通訊協定](https://microsoft.github.io/debug-adapter-" +"protocol/)允許在任何支援的微控制器上執行 VSCode 及其他 IDE 偵錯程式碼。" -#: src/bare-metal/microcontrollers/probe-rs.md:25 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "cargo-embed is a binary built using the probe-rs library." -msgstr "" +msgstr "cargo-embed 是使用 probe-rs 程式庫建構的二進位檔。" -#: src/bare-metal/microcontrollers/probe-rs.md:26 +#: src/bare-metal/microcontrollers/probe-rs.md msgid "" "RTT (Real Time Transfers) is a mechanism to transfer data between the debug " "host and the target through a number of ringbuffers." msgstr "" +"RTT (即時傳輸) 這種機制是透過多個環形緩衝區,在偵錯主機和目標之間傳輸資料。" -#: src/bare-metal/microcontrollers/debugging.md:3 -msgid "Embed.toml:" -msgstr "" +#: src/bare-metal/microcontrollers/debugging.md +msgid "_Embed.toml_:" +msgstr "Embed.toml:" -#: src/bare-metal/microcontrollers/debugging.md:5 -msgid "" -"```toml\n" -"[default.general]\n" -"chip = \"nrf52833_xxAA\"\n" -"\n" -"[debug.gdb]\n" -"enabled = true\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/debugging.md:13 +#: src/bare-metal/microcontrollers/debugging.md msgid "In one terminal under `src/bare-metal/microcontrollers/examples/`:" -msgstr "" +msgstr "在 `src/bare-metal/microcontrollers/examples/` 底下的一個終端機中:" -#: src/bare-metal/microcontrollers/debugging.md:15 -msgid "" -"```sh\n" -"cargo embed --bin board_support debug\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/debugging.md:19 +#: src/bare-metal/microcontrollers/debugging.md msgid "In another terminal in the same directory:" -msgstr "" +msgstr "在相同目錄的另一個終端機中:" -#: src/bare-metal/microcontrollers/debugging.md:21 -msgid "" -"```sh\n" -"gdb-multiarch target/thumbv7em-none-eabihf/debug/board_support --eval-" -"command=\"target remote :1337\"\n" -"```" -msgstr "" +#: src/bare-metal/microcontrollers/debugging.md +msgid "On gLinux or Debian:" +msgstr "使用 gLinux 或 Debian:" -#: src/bare-metal/microcontrollers/debugging.md:27 +#: src/bare-metal/microcontrollers/debugging.md msgid "In GDB, try running:" -msgstr "" +msgstr "在 GDB 中,嘗試執行下列指令:" -#: src/bare-metal/microcontrollers/debugging.md:29 -msgid "" -"```gdb\n" -"b src/bin/board_support.rs:29\n" -"b src/bin/board_support.rs:30\n" -"b src/bin/board_support.rs:32\n" -"c\n" -"c\n" -"c\n" -"```" -msgstr "" - -#: src/bare-metal/microcontrollers/other-projects.md:1 -#: src/bare-metal/aps/other-projects.md:1 +#: src/bare-metal/microcontrollers/other-projects.md +#: src/bare-metal/aps/other-projects.md msgid "Other projects" -msgstr "" +msgstr "其他專案" -#: src/bare-metal/microcontrollers/other-projects.md:3 +#: src/bare-metal/microcontrollers/other-projects.md msgid "[RTIC](https://rtic.rs/)" -msgstr "" +msgstr "[RTIC](https://rtic.rs/)" -#: src/bare-metal/microcontrollers/other-projects.md:4 +#: src/bare-metal/microcontrollers/other-projects.md msgid "\"Real-Time Interrupt-driven Concurrency\"" -msgstr "" +msgstr "「即時中斷驅動並行」" -#: src/bare-metal/microcontrollers/other-projects.md:5 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "Shared resource management, message passing, task scheduling, timer queue" -msgstr "" +msgstr "共用資源管理、訊息傳遞、工作排程、計時器佇列" -#: src/bare-metal/microcontrollers/other-projects.md:6 +#: src/bare-metal/microcontrollers/other-projects.md msgid "[Embassy](https://embassy.dev/)" -msgstr "" +msgstr "[Embassy](https://embassy.dev/)" -#: src/bare-metal/microcontrollers/other-projects.md:7 +#: src/bare-metal/microcontrollers/other-projects.md msgid "`async` executors with priorities, timers, networking, USB" -msgstr "" +msgstr "具有優先順序、計時器、網路、USB 功能的 `async` 執行器" -#: src/bare-metal/microcontrollers/other-projects.md:8 +#: src/bare-metal/microcontrollers/other-projects.md msgid "[TockOS](https://www.tockos.org/documentation/getting-started)" -msgstr "" +msgstr "[TockOS](https://www.tockos.org/documentation/getting-started)" -#: src/bare-metal/microcontrollers/other-projects.md:9 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "Security-focused RTOS with preemptive scheduling and Memory Protection Unit " "support" -msgstr "" +msgstr "注重安全性的 RTOS,提供先占式排程功能,並支援記憶體保護單元" -#: src/bare-metal/microcontrollers/other-projects.md:10 +#: src/bare-metal/microcontrollers/other-projects.md msgid "[Hubris](https://hubris.oxide.computer/)" -msgstr "" +msgstr "[Hubris](https://hubris.oxide.computer/)" -#: src/bare-metal/microcontrollers/other-projects.md:11 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "Microkernel RTOS from Oxide Computer Company with memory protection, " "unprivileged drivers, IPC" msgstr "" +"Oxide Computer Company 的微核心 RTOS,提供記憶體防護、未具有特權的驅動程式、" +"IPC" -#: src/bare-metal/microcontrollers/other-projects.md:12 +#: src/bare-metal/microcontrollers/other-projects.md msgid "[Bindings for FreeRTOS](https://github.com/lobaro/FreeRTOS-rust)" -msgstr "" +msgstr "[FreeRTOS 繫結](https://github.com/lobaro/FreeRTOS-rust)" -#: src/bare-metal/microcontrollers/other-projects.md:13 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "Some platforms have `std` implementations, e.g. [esp-idf](https://esp-rs." "github.io/book/overview/using-the-standard-library.html)." msgstr "" +"部分平台提供 `std` 實作項目,例如 [esp-idf](https://esp-rs.github.io/book/" +"overview/using-the-standard-library.html)。" -#: src/bare-metal/microcontrollers/other-projects.md:18 +#: src/bare-metal/microcontrollers/other-projects.md msgid "RTIC can be considered either an RTOS or a concurrency framework." -msgstr "" +msgstr "RTIC 可視為 RTOS 或並行架構。" -#: src/bare-metal/microcontrollers/other-projects.md:19 +#: src/bare-metal/microcontrollers/other-projects.md msgid "It doesn't include any HALs." -msgstr "" +msgstr "其中不包含任何 HAL。" -#: src/bare-metal/microcontrollers/other-projects.md:20 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "It uses the Cortex-M NVIC (Nested Virtual Interrupt Controller) for " "scheduling rather than a proper kernel." msgstr "" +"排程時會使用 Cortex-M NVIC (巢狀虛擬中斷控制器),而不是使用適當的核心。" -#: src/bare-metal/microcontrollers/other-projects.md:22 +#: src/bare-metal/microcontrollers/other-projects.md msgid "Cortex-M only." -msgstr "" +msgstr "僅限 Cortex-M。" -#: src/bare-metal/microcontrollers/other-projects.md:23 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "Google uses TockOS on the Haven microcontroller for Titan security keys." -msgstr "" +msgstr "Google 會針對 Titan 安全金鑰,在 Haven 微控制器上使用 TockOS。" -#: src/bare-metal/microcontrollers/other-projects.md:24 +#: src/bare-metal/microcontrollers/other-projects.md msgid "" "FreeRTOS is mostly written in C, but there are Rust bindings for writing " "applications." -msgstr "" +msgstr "FreeRTOS 大部分以 C 語言編寫,但也有適合編寫應用程式的 Rust 繫結。" -#: src/exercises/bare-metal/morning.md:3 +#: src/exercises/bare-metal/morning.md msgid "" "We will read the direction from an I2C compass, and log the readings to a " "serial port." -msgstr "" +msgstr "我們將讀取 I2C 羅盤中的方向,並將讀數記錄到序列埠。" -#: src/exercises/bare-metal/compass.md:3 +#: src/exercises/bare-metal/morning.md src/exercises/concurrency/morning.md +msgid "" +"After looking at the exercises, you can look at the [solutions](solutions-" +"morning.md) provided." +msgstr "完成練習後,您可以看看我們提供的[解決方案](solutions-morning.md)。" + +#: src/exercises/bare-metal/compass.md msgid "" "We will read the direction from an I2C compass, and log the readings to a " "serial port. If you have time, try displaying it on the LEDs somehow too, or " "use the buttons somehow." msgstr "" +"我們將讀取 I2C 羅盤上的方向,並將讀數記錄到序列埠。如有時間,可以試著顯示在 " +"LED 上,或以某種方法使用按鈕。" -#: src/exercises/bare-metal/compass.md:6 +#: src/exercises/bare-metal/compass.md msgid "Hints:" -msgstr "" +msgstr "提示:" -#: src/exercises/bare-metal/compass.md:8 +#: src/exercises/bare-metal/compass.md msgid "" "Check the documentation for the [`lsm303agr`](https://docs.rs/lsm303agr/" "latest/lsm303agr/) and [`microbit-v2`](https://docs.rs/microbit-v2/latest/" "microbit/) crates, as well as the [micro:bit hardware](https://tech.microbit." "org/hardware/)." msgstr "" +"參閱 [`lsm303agr`](https://docs.rs/lsm303agr/latest/lsm303agr/) 和 " +"[`microbit-v2`](https://docs.rs/microbit-v2/latest/microbit/) Crate 的說明文" +"件,並瞭解 [micro:bit 硬體](https://tech.microbit.org/hardware/)。" -#: src/exercises/bare-metal/compass.md:11 +#: src/exercises/bare-metal/compass.md msgid "" "The LSM303AGR Inertial Measurement Unit is connected to the internal I2C bus." -msgstr "" +msgstr "LSM303AGR 慣性測量單元已連接至內部 I2C 匯流排。" -#: src/exercises/bare-metal/compass.md:12 +#: src/exercises/bare-metal/compass.md msgid "" "TWI is another name for I2C, so the I2C master peripheral is called TWIM." -msgstr "" +msgstr "TWI 是 I2C 的別名,所以 I2C 主周邊裝置的名稱是 TWIM。" -#: src/exercises/bare-metal/compass.md:13 +#: src/exercises/bare-metal/compass.md msgid "" "The LSM303AGR driver needs something implementing the `embedded_hal::" "blocking::i2c::WriteRead` trait. The [`microbit::hal::Twim`](https://docs.rs/" "microbit-v2/latest/microbit/hal/struct.Twim.html) struct implements this." msgstr "" +"LSM303AGR 驅動程式需要某個實作 `embedded_hal::blocking::i2c::WriteRead` 特徵" +"的項目。[`microbit::hal::Twim`](https://docs.rs/microbit-v2/latest/microbit/" +"hal/struct.Twim.html) 結構體實作此特徵。" -#: src/exercises/bare-metal/compass.md:17 +#: src/exercises/bare-metal/compass.md msgid "" "You have a [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/" "struct.Board.html) struct with fields for the various pins and peripherals." msgstr "" +"您有 [`microbit::Board`](https://docs.rs/microbit-v2/latest/microbit/struct." +"Board.html) 結構體,其中包含各種接腳和周邊裝置的欄位。" -#: src/exercises/bare-metal/compass.md:19 +#: src/exercises/bare-metal/compass.md msgid "" "You can also look at the [nRF52833 datasheet](https://infocenter.nordicsemi." "com/pdf/nRF52833_PS_v1.5.pdf) if you want, but it shouldn't be necessary for " "this exercise." msgstr "" +"您也可以視需要查看 [nRF52833 規格書](https://infocenter.nordicsemi.com/pdf/" +"nRF52833_PS_v1.5.pdf),但在這項練習中並非必要。" -#: src/exercises/bare-metal/compass.md:23 +#: src/exercises/bare-metal/compass.md msgid "" "Download the [exercise template](../../comprehensive-rust-exercises.zip) and " "look in the `compass` directory for the following files." msgstr "" +"請下載[練習範本](../../comprehensive-rust-exercises.zip),並在 `compass` 目錄" +"中查看下列檔案。" -#: src/exercises/bare-metal/compass.md:26 src/exercises/bare-metal/rtc.md:19 -msgid "`src/main.rs`:" -msgstr "" +#: src/exercises/bare-metal/compass.md src/exercises/bare-metal/rtc.md +msgid "_src/main.rs_:" +msgstr "_src/main.rs_:" -#: src/exercises/bare-metal/compass.md:30 -msgid "" -"```rust,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use core::fmt::Write;\n" -"use cortex_m_rt::entry;\n" -"use microbit::{hal::uarte::{Baudrate, Parity, Uarte}, Board};\n" -"\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let board = Board::take().unwrap();\n" -"\n" -" // Configure serial port.\n" -" let mut serial = Uarte::new(\n" -" board.UARTE0,\n" -" board.uart.into(),\n" -" Parity::EXCLUDED,\n" -" Baudrate::BAUD115200,\n" -" );\n" -"\n" -" // Set up the I2C controller and Inertial Measurement Unit.\n" -" // TODO\n" -"\n" -" writeln!(serial, \"Ready.\").unwrap();\n" -"\n" -" loop {\n" -" // Read compass data and log it to the serial port.\n" -" // TODO\n" -" }\n" -"}\n" -"```" -msgstr "" +#: src/exercises/bare-metal/compass.md src/exercises/bare-metal/rtc.md +msgid "_Cargo.toml_ (you shouldn't need to change this):" +msgstr "Cargo.toml (您應該不需要變更此項目):" -#: src/exercises/bare-metal/compass.md:64 src/exercises/bare-metal/rtc.md:385 -msgid "`Cargo.toml` (you shouldn't need to change this):" -msgstr "" +#: src/exercises/bare-metal/compass.md +msgid "_Embed.toml_ (you shouldn't need to change this):" +msgstr "Embed.toml (您應該不需要變更此項目):" -#: src/exercises/bare-metal/compass.md:68 -msgid "" -"```toml\n" -"[workspace]\n" -"\n" -"[package]\n" -"name = \"compass\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"publish = false\n" -"\n" -"[dependencies]\n" -"cortex-m-rt = \"0.7.3\"\n" -"embedded-hal = \"0.2.6\"\n" -"lsm303agr = \"0.2.2\"\n" -"microbit-v2 = \"0.13.0\"\n" -"panic-halt = \"0.2.0\"\n" -"```" -msgstr "" +#: src/exercises/bare-metal/compass.md src/exercises/bare-metal/rtc.md +msgid "_.cargo/config.toml_ (you shouldn't need to change this):" +msgstr ".cargo/config.toml (您應該不需要變更此項目):" -#: src/exercises/bare-metal/compass.md:85 -msgid "`Embed.toml` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/compass.md:89 -msgid "" -"```toml\n" -"[default.general]\n" -"chip = \"nrf52833_xxAA\"\n" -"\n" -"[debug.gdb]\n" -"enabled = true\n" -"\n" -"[debug.reset]\n" -"halt_afterwards = true\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/compass.md:100 src/exercises/bare-metal/rtc.md:985 -msgid "`.cargo/config.toml` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/compass.md:104 -msgid "" -"```toml\n" -"[build]\n" -"target = \"thumbv7em-none-eabihf\" # Cortex-M4F\n" -"\n" -"[target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))']\n" -"rustflags = [\"-C\", \"link-arg=-Tlink.x\"]\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/compass.md:112 +#: src/exercises/bare-metal/compass.md msgid "See the serial output on Linux with:" -msgstr "" +msgstr "使用下列指令在 Linux 查看序列輸出內容:" -#: src/exercises/bare-metal/compass.md:114 -msgid "" -"```sh\n" -"picocom --baud 115200 --imap lfcrlf /dev/ttyACM0\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/compass.md:118 +#: src/exercises/bare-metal/compass.md msgid "" "Or on Mac OS something like (the device name may be slightly different):" -msgstr "" +msgstr "或在 macOS 上使用類似如下的指令 (裝置名稱可能略有不同):" -#: src/exercises/bare-metal/compass.md:120 -msgid "" -"```sh\n" -"picocom --baud 115200 --imap lfcrlf /dev/tty.usbmodem14502\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/compass.md:124 +#: src/exercises/bare-metal/compass.md msgid "Use Ctrl+A Ctrl+Q to quit picocom." -msgstr "" +msgstr "按下 Ctrl + A、Ctrl + Q 鍵即可退出 picocom。" -#: src/bare-metal/aps.md:1 +#: src/exercises/bare-metal/solutions-morning.md +msgid "Bare Metal Rust Morning Exercise" +msgstr "Rust 裸機開發:上午練習" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "([back to exercise](compass.md))" +msgstr "([返回練習](compass.md))" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "// Configure serial port.\n" +msgstr "// Configure serial port.\n" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "// Use the system timer as a delay provider.\n" +msgstr "// Use the system timer as a delay provider.\n" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "// Set up the I2C controller and Inertial Measurement Unit.\n" +msgstr "// Set up the I2C controller and Inertial Measurement Unit.\n" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "\"Setting up IMU...\"" +msgstr "\"Setting up IMU...\"" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "// Set up display and timer.\n" +msgstr "// Set up display and timer.\n" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "\"Ready.\"" +msgstr "\"Ready.\"" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "// Read compass data and log it to the serial port.\n" +msgstr "// Read compass data and log it to the serial port.\n" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "\"{},{},{}\\t{},{},{}\"" +msgstr "\"{},{},{}\\t{},{},{}\"" + +#: src/exercises/bare-metal/solutions-morning.md +msgid "" +"// If button A is pressed, switch to the next mode and briefly blink all " +"LEDs\n" +" // on.\n" +msgstr "" +"// If button A is pressed, switch to the next mode and briefly blink all " +"LEDs\n" +" // on.\n" + +#: src/bare-metal/aps.md msgid "Application processors" -msgstr "" +msgstr "應用程式處理器" -#: src/bare-metal/aps.md:3 +#: src/bare-metal/aps.md msgid "" "So far we've talked about microcontrollers, such as the Arm Cortex-M series. " "Now let's try writing something for Cortex-A. For simplicity we'll just work " "with QEMU's aarch64 ['virt'](https://qemu-project.gitlab.io/qemu/system/arm/" "virt.html) board." msgstr "" +"目前我們已介紹過微控制器,例如 Arm Cortex-M 系列產品,現在來試著為 Cortex-A " +"撰寫一些內容。為求簡單,我們會使用 QEMU 的 aarch64 ['virt'](https://qemu-" +"project.gitlab.io/qemu/system/arm/virt.html) 開發板。" -#: src/bare-metal/aps.md:9 +#: src/bare-metal/aps.md msgid "" "Broadly speaking, microcontrollers don't have an MMU or multiple levels of " "privilege (exception levels on Arm CPUs, rings on x86), while application " "processors do." msgstr "" +"普遍來說,微控制器並沒有 MMU 或多個權限層級 (Arm CPU 上的例外狀況層級、x86 上" +"的環),但應用程式處理器有。" -#: src/bare-metal/aps.md:11 +#: src/bare-metal/aps.md msgid "" "QEMU supports emulating various different machines or board models for each " "architecture. The 'virt' board doesn't correspond to any particular real " "hardware, but is designed purely for virtual machines." msgstr "" +"QEMU 可針對每個架構模擬不同的機器或開發板模型。'virt' 開發板並無對應至任何特" +"定的真實硬體,而是專為虛擬機器設計。" -#: src/bare-metal/aps/inline-assembly.md:1 -msgid "Inline assembly" -msgstr "" - -#: src/bare-metal/aps/inline-assembly.md:3 +#: src/bare-metal/aps/entry-point.md msgid "" -"Sometimes we need to use assembly to do things that aren't possible with " -"Rust code. For example, to make an " -msgstr "" +"Before we can start running Rust code, we need to do some initialisation." +msgstr "我們需要先完成一些初始化作業,才能開始執行 Rust 程式碼。" -#: src/bare-metal/aps/inline-assembly.md:4 -msgid "HVC" -msgstr "" - -#: src/bare-metal/aps/inline-assembly.md:4 -msgid " to tell the firmware to power off the system:" -msgstr "" - -#: src/bare-metal/aps/inline-assembly.md:6 +#: src/bare-metal/aps/entry-point.md msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" +"```armasm\n" +".section .init.entry, \"ax\"\n" +".global entry\n" +"entry:\n" +" /*\n" +" * Load and apply the memory management configuration, ready to enable " +"MMU and\n" +" * caches.\n" +" */\n" +" adrp x30, idmap\n" +" msr ttbr0_el1, x30\n" "\n" -"use core::arch::asm;\n" -"use core::panic::PanicInfo;\n" +" mov_i x30, .Lmairval\n" +" msr mair_el1, x30\n" "\n" -"mod exceptions;\n" +" mov_i x30, .Ltcrval\n" +" /* Copy the supported PA range into TCR_EL1.IPS. */\n" +" mrs x29, id_aa64mmfr0_el1\n" +" bfi x30, x29, #32, #4\n" "\n" -"const PSCI_SYSTEM_OFF: u32 = 0x84000008;\n" +" msr tcr_el1, x30\n" "\n" -"#[no_mangle]\n" -"extern \"C\" fn main(_x0: u64, _x1: u64, _x2: u64, _x3: u64) {\n" -" // Safe because this only uses the declared registers and doesn't do\n" -" // anything with memory.\n" -" unsafe {\n" -" asm!(\"hvc #0\",\n" -" inout(\"w0\") PSCI_SYSTEM_OFF => _,\n" -" inout(\"w1\") 0 => _,\n" -" inout(\"w2\") 0 => _,\n" -" inout(\"w3\") 0 => _,\n" -" inout(\"w4\") 0 => _,\n" -" inout(\"w5\") 0 => _,\n" -" inout(\"w6\") 0 => _,\n" -" inout(\"w7\") 0 => _,\n" -" options(nomem, nostack)\n" -" );\n" -" }\n" +" mov_i x30, .Lsctlrval\n" "\n" -" loop {}\n" -"}\n" +" /*\n" +" * Ensure everything before this point has completed, then invalidate " +"any\n" +" * potentially stale local TLB entries before they start being used.\n" +" */\n" +" isb\n" +" tlbi vmalle1\n" +" ic iallu\n" +" dsb nsh\n" +" isb\n" +"\n" +" /*\n" +" * Configure sctlr_el1 to enable MMU and cache and don't proceed until " +"this\n" +" * has completed.\n" +" */\n" +" msr sctlr_el1, x30\n" +" isb\n" +"\n" +" /* Disable trapping floating point access in EL1. */\n" +" mrs x30, cpacr_el1\n" +" orr x30, x30, #(0x3 << 20)\n" +" msr cpacr_el1, x30\n" +" isb\n" +"\n" +" /* Zero out the bss section. */\n" +" adr_l x29, bss_begin\n" +" adr_l x30, bss_end\n" +"0: cmp x29, x30\n" +" b.hs 1f\n" +" stp xzr, xzr, [x29], #16\n" +" b 0b\n" +"\n" +"1: /* Prepare the stack. */\n" +" adr_l x30, boot_stack_end\n" +" mov sp, x30\n" +"\n" +" /* Set up exception vector. */\n" +" adr x30, vector_table_el1\n" +" msr vbar_el1, x30\n" +"\n" +" /* Call into Rust code. */\n" +" bl main\n" +"\n" +" /* Loop forever waiting for interrupts. */\n" +"2: wfi\n" +" b 2b\n" "```" msgstr "" +"```armasm\n" +".section .init.entry, \"ax\"\n" +".global entry\n" +"entry:\n" +" /*\n" +" * Load and apply the memory management configuration, ready to enable " +"MMU and\n" +" * caches.\n" +" */\n" +" adrp x30, idmap\n" +" msr ttbr0_el1, x30\n" +"\n" +" mov_i x30, .Lmairval\n" +" msr mair_el1, x30\n" +"\n" +" mov_i x30, .Ltcrval\n" +" /* Copy the supported PA range into TCR_EL1.IPS. */\n" +" mrs x29, id_aa64mmfr0_el1\n" +" bfi x30, x29, #32, #4\n" +"\n" +" msr tcr_el1, x30\n" +"\n" +" mov_i x30, .Lsctlrval\n" +"\n" +" /*\n" +" * Ensure everything before this point has completed, then invalidate " +"any\n" +" * potentially stale local TLB entries before they start being used.\n" +" */\n" +" isb\n" +" tlbi vmalle1\n" +" ic iallu\n" +" dsb nsh\n" +" isb\n" +"\n" +" /*\n" +" * Configure sctlr_el1 to enable MMU and cache and don't proceed until " +"this\n" +" * has completed.\n" +" */\n" +" msr sctlr_el1, x30\n" +" isb\n" +"\n" +" /* Disable trapping floating point access in EL1. */\n" +" mrs x30, cpacr_el1\n" +" orr x30, x30, #(0x3 << 20)\n" +" msr cpacr_el1, x30\n" +" isb\n" +"\n" +" /* Zero out the bss section. */\n" +" adr_l x29, bss_begin\n" +" adr_l x30, bss_end\n" +"0: cmp x29, x30\n" +" b.hs 1f\n" +" stp xzr, xzr, [x29], #16\n" +" b 0b\n" +"\n" +"1: /* Prepare the stack. */\n" +" adr_l x30, boot_stack_end\n" +" mov sp, x30\n" +"\n" +" /* Set up exception vector. */\n" +" adr x30, vector_table_el1\n" +" msr vbar_el1, x30\n" +"\n" +" /* Call into Rust code. */\n" +" bl main\n" +"\n" +" /* Loop forever waiting for interrupts. */\n" +"2: wfi\n" +" b 2b\n" +"```" -#: src/bare-metal/aps/inline-assembly.md:39 +#: src/bare-metal/aps/entry-point.md +msgid "" +"This is the same as it would be for C: initialising the processor state, " +"zeroing the BSS, and setting up the stack pointer." +msgstr "" +"這與使用 C 時相同:將處理器狀態初始化、將 BSS 設為零,以及設定堆疊指標。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"The BSS (block starting symbol, for historical reasons) is the part of the " +"object file which containing statically allocated variables which are " +"initialised to zero. They are omitted from the image, to avoid wasting space " +"on zeroes. The compiler assumes that the loader will take care of zeroing " +"them." +msgstr "" +"BSS (區塊起始符號,因歷史因素而存在) 是物件檔案的一部分,含有初始化為零的靜態" +"分配變數。映像檔會省略這些變數,以免浪費空間儲存零。編譯器會假設由載入器負責" +"將變數初始化為零。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"The BSS may already be zeroed, depending on how memory is initialised and " +"the image is loaded, but we zero it to be sure." +msgstr "" +"視記憶體初始化及映像檔載入方式而定,BSS 可能已為零,但為了確定,我們會將它設" +"為零。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"We need to enable the MMU and cache before reading or writing any memory. If " +"we don't:" +msgstr "我們需要啟用 MMU 和快取,才能讀取或寫入任何記憶體。如果不這樣做:" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"Unaligned accesses will fault. We build the Rust code for the `aarch64-" +"unknown-none` target which sets `+strict-align` to prevent the compiler " +"generating unaligned accesses, so it should be fine in this case, but this " +"is not necessarily the case in general." +msgstr "" +"未對齊的存取會發生錯誤。我們是為 `aarch64-unknown-none` 目標建構 Rust 程式" +"碼,這會設定 `+strict-align`,防止編譯器產生未對齊的存取,因此在本例中應該不" +"會出錯,但這不一定是一般情況。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"If it were running in a VM, this can lead to cache coherency issues. The " +"problem is that the VM is accessing memory directly with the cache disabled, " +"while the host has cacheable aliases to the same memory. Even if the host " +"doesn't explicitly access the memory, speculative accesses can lead to cache " +"fills, and then changes from one or the other will get lost when the cache " +"is cleaned or the VM enables the cache. (Cache is keyed by physical address, " +"not VA or IPA.)" +msgstr "" +"如果是在 VM 中執行,可能會導致快取一致性問題。問題在於 VM 會在快取已停用時直" +"接存取記憶體,而主機具有相同記憶體的可快取別名。即使主機未明確存取記憶體,推" +"測存取行為仍可能導致快取填補,而當快取遭到清理或 VM 啟用快取時,存取之間的變" +"更就會遺失 (快取是以實體位址做為索引鍵,並非使用 VA 或 IPA)。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"For simplicity, we just use a hardcoded pagetable (see `idmap.S`) which " +"identity maps the first 1 GiB of address space for devices, the next 1 GiB " +"for DRAM, and another 1 GiB higher up for more devices. This matches the " +"memory layout that QEMU uses." +msgstr "" +"為求簡單,我們只使用寫死的分頁表 (見 `idmap.S`),其中前 1 GiB 的位址空間是對" +"應至裝置、接下來 1 GiB 是對應至 DRAM,另外 1 GiB 以上則適用更多裝置。這符合 " +"QEMU 使用的記憶體布局。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"We also set up the exception vector (`vbar_el1`), which we'll see more about " +"later." +msgstr "我們也會設定例外狀況向量 (`vbar_el1`),稍後將進一步說明。" + +#: src/bare-metal/aps/entry-point.md +msgid "" +"All examples this afternoon assume we will be running at exception level 1 " +"(EL1). If you need to run at a different exception level you'll need to " +"modify `entry.S` accordingly." +msgstr "" +"今天下午的所有例子都假設我們會在例外狀況層級 1 (EL1) 執行。如要在不同的例外狀" +"況層級執行,就需據以修改 `entry.S`。" + +#: src/bare-metal/aps/inline-assembly.md +msgid "Inline assembly" +msgstr "行內組語" + +#: src/bare-metal/aps/inline-assembly.md +msgid "" +"Sometimes we need to use assembly to do things that aren't possible with " +"Rust code. For example, to make an HVC (hypervisor call) to tell the " +"firmware to power off the system:" +msgstr "" +"有時候,我們需要使用組語,才能執行 Rust 程式碼無法執行的作業。舉例來說,如要" +"發出 HVC (管理程序呼叫) 指示韌體關閉系統:" + +#: src/bare-metal/aps/inline-assembly.md +msgid "" +"// Safe because this only uses the declared registers and doesn't do\n" +" // anything with memory.\n" +msgstr "" +"// Safe because this only uses the declared registers and doesn't do\n" +" // anything with memory.\n" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"hvc #0\"" +msgstr "\"hvc #0\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w0\"" +msgstr "\"w0\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w1\"" +msgstr "\"w1\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w2\"" +msgstr "\"w2\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w3\"" +msgstr "\"w3\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w4\"" +msgstr "\"w4\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w5\"" +msgstr "\"w5\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w6\"" +msgstr "\"w6\"" + +#: src/bare-metal/aps/inline-assembly.md +msgid "\"w7\"" +msgstr "\"w7\"" + +#: src/bare-metal/aps/inline-assembly.md msgid "" "(If you actually want to do this, use the [`smccc`](https://crates.io/crates/" "smccc) crate which has wrappers for all these functions.)" msgstr "" +"(如果您確實想執行這項操作,請使用 [`smccc`](https://crates.io/crates/smccc) " +"Crate,其中包含所有這些函式的包裝函式。)" -#: src/bare-metal/aps/inline-assembly.md:43 +#: src/bare-metal/aps/inline-assembly.md msgid "" "PSCI is the Arm Power State Coordination Interface, a standard set of " "functions to manage system and CPU power states, among other things. It is " "implemented by EL3 firmware and hypervisors on many systems." msgstr "" +"PSCI 是 Arm 電源狀態協調介面,這組標準函式可管理系統和 CPU 電源狀態及其他項" +"目,是由 EL3 韌體和管理程序在許多系統上實作。" -#: src/bare-metal/aps/inline-assembly.md:46 +#: src/bare-metal/aps/inline-assembly.md msgid "" "The `0 => _` syntax means initialise the register to 0 before running the " "inline assembly code, and ignore its contents afterwards. We need to use " "`inout` rather than `in` because the call could potentially clobber the " "contents of the registers." msgstr "" +"`0 => _` 語法是指在行內組語程式碼執行之前,將暫存器初始化為 0,之後就忽略其內" +"容。我們需要使用 `inout` (而非 `in`),因為呼叫可能會破壞暫存器的內容。" -#: src/bare-metal/aps/inline-assembly.md:49 +#: src/bare-metal/aps/inline-assembly.md msgid "" "This `main` function needs to be `#[no_mangle]` and `extern \"C\"` because " "it is called from our entry point in `entry.S`." msgstr "" +"這個 `main` 函式需為 `#[no_mangle]` 和 `extern \"C\"`,因為此函式是從 `entry." +"S` 的進入點呼叫。" -#: src/bare-metal/aps/inline-assembly.md:51 +#: src/bare-metal/aps/inline-assembly.md msgid "" "`_x0`–`_x3` are the values of registers `x0`–`x3`, which are conventionally " "used by the bootloader to pass things like a pointer to the device tree. " @@ -14734,83 +18031,88 @@ msgid "" "arguments passed to a function, so `entry.S` doesn't need to do anything " "special except make sure it doesn't change these registers." msgstr "" +"`_x0` 到 `_x3` 是暫存器 `x0` 到 `x3` 的值。按照慣例,系統啟動載入程式會使用這" +"些值,將指標等項目傳遞給裝置樹狀結構。根據標準的 aarch64 呼叫慣例 (即 " +"`extern \"C\"` 指定使用的項目),前 8 個傳遞至函式的引數會使用暫存器 `x0` 到 " +"`x7`,因此 `entry.S` 不需執行任何特殊操作,只要確保不會變更這些暫存器。" -#: src/bare-metal/aps/inline-assembly.md:56 +#: src/bare-metal/aps/inline-assembly.md msgid "" "Run the example in QEMU with `make qemu_psci` under `src/bare-metal/aps/" "examples`." msgstr "" +"使用 `src/bare-metal/aps/examples` 下的 `make qemu_psci`,在 QEMU 中執行範" +"例。" -#: src/bare-metal/aps/mmio.md:1 +#: src/bare-metal/aps/mmio.md msgid "Volatile memory access for MMIO" -msgstr "" +msgstr "MMIO 揮發性記憶體存取" -#: src/bare-metal/aps/mmio.md:3 +#: src/bare-metal/aps/mmio.md msgid "Use `pointer::read_volatile` and `pointer::write_volatile`." -msgstr "" +msgstr "使用 `pointer::read_volatile` 和 `pointer::write_volatile`。" -#: src/bare-metal/aps/mmio.md:4 +#: src/bare-metal/aps/mmio.md msgid "Never hold a reference." -msgstr "" +msgstr "請勿保留參照。" -#: src/bare-metal/aps/mmio.md:5 +#: src/bare-metal/aps/mmio.md msgid "" "`addr_of!` lets you get fields of structs without creating an intermediate " "reference." -msgstr "" +msgstr "`addr_of!` 可用來取得結構體的欄位,而不必建立中繼參照。" -#: src/bare-metal/aps/mmio.md:9 +#: src/bare-metal/aps/mmio.md msgid "" "Volatile access: read or write operations may have side-effects, so prevent " "the compiler or hardware from reordering, duplicating or eliding them." msgstr "" +"揮發性存取:讀取或寫入作業可能會有副作用,因此請避免編譯器或硬體遭到重新排" +"序、複製或省略。" -#: src/bare-metal/aps/mmio.md:11 +#: src/bare-metal/aps/mmio.md msgid "" "Usually if you write and then read, e.g. via a mutable reference, the " "compiler may assume that the value read is the same as the value just " "written, and not bother actually reading memory." msgstr "" +"通常,如果您在寫入後讀取 (例如透過可變動參照),編譯器可能會假設讀取的值與剛寫" +"入的值相同,而不實際讀取記憶體。" -#: src/bare-metal/aps/mmio.md:13 +#: src/bare-metal/aps/mmio.md msgid "" "Some existing crates for volatile access to hardware do hold references, but " "this is unsound. Whenever a reference exist, the compiler may choose to " "dereference it." msgstr "" +"有些用於硬體揮發性存取的現有 Crate 確實會保留參照,但這樣不安全。每當有參照存" +"在時,編譯器可能會選擇解除參照。" -#: src/bare-metal/aps/mmio.md:15 +#: src/bare-metal/aps/mmio.md msgid "" "Use the `addr_of!` macro to get struct field pointers from a pointer to the " "struct." -msgstr "" +msgstr "使用 `addr_of!` 巨集,從結構體的指標取得結構體欄位指標。" -#: src/bare-metal/aps/uart.md:1 +#: src/bare-metal/aps/uart.md msgid "Let's write a UART driver" -msgstr "" +msgstr "編寫 UART 驅動程式" -#: src/bare-metal/aps/uart.md:3 +#: src/bare-metal/aps/uart.md msgid "" "The QEMU 'virt' machine has a [PL011](https://developer.arm.com/" "documentation/ddi0183/g) UART, so let's write a driver for that." msgstr "" +"QEMU 'virt' 機器搭載 [PL011](https://developer.arm.com/documentation/ddi0183/" +"g) UART,所以我們要為此編寫驅動程式。" -#: src/bare-metal/aps/uart.md:5 +#: src/bare-metal/aps/uart.md +msgid "/// Minimal driver for a PL011 UART.\n" +msgstr "/// Minimal driver for a PL011 UART.\n" + +#: src/bare-metal/aps/uart.md src/bare-metal/aps/better-uart/driver.md msgid "" -"```rust,editable\n" -"const FLAG_REGISTER_OFFSET: usize = 0x18;\n" -"const FR_BUSY: u8 = 1 << 3;\n" -"const FR_TXFF: u8 = 1 << 5;\n" -"\n" -"/// Minimal driver for a PL011 UART.\n" -"#[derive(Debug)]\n" -"pub struct Uart {\n" -" base_address: *mut u8,\n" -"}\n" -"\n" -"impl Uart {\n" -" /// Constructs a new instance of the UART driver for a PL011 device at " -"the\n" +"/// Constructs a new instance of the UART driver for a PL011 device at the\n" " /// given base address.\n" " ///\n" " /// # Safety\n" @@ -14820,37 +18122,43 @@ msgid "" " /// PL011 device, which must be mapped into the address space of the " "process\n" " /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u8) -> Self {\n" -" Self { base_address }\n" -" }\n" -"\n" -" /// Writes a single byte to the UART.\n" -" pub fn write_byte(&self, byte: u8) {\n" -" // Wait until there is room in the TX buffer.\n" -" while self.read_flag_register() & FR_TXFF != 0 {}\n" -"\n" -" // Safe because we know that the base address points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe {\n" -" // Write to the TX buffer.\n" -" self.base_address.write_volatile(byte);\n" -" }\n" -"\n" -" // Wait until the UART is no longer busy.\n" -" while self.read_flag_register() & FR_BUSY != 0 {}\n" -" }\n" -"\n" -" fn read_flag_register(&self) -> u8 {\n" -" // Safe because we know that the base address points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe { self.base_address.add(FLAG_REGISTER_OFFSET)." -"read_volatile() }\n" -" }\n" -"}\n" -"```" msgstr "" +"/// Constructs a new instance of the UART driver for a PL011 device at the\n" +" /// given base address.\n" +" ///\n" +" /// # Safety\n" +" ///\n" +" /// The given base address must point to the 8 MMIO control registers of " +"a\n" +" /// PL011 device, which must be mapped into the address space of the " +"process\n" +" /// as device memory and not have any other aliases.\n" -#: src/bare-metal/aps/uart.md:55 +#: src/bare-metal/aps/uart.md src/bare-metal/aps/better-uart/driver.md +msgid "/// Writes a single byte to the UART.\n" +msgstr "/// Writes a single byte to the UART.\n" + +#: src/bare-metal/aps/uart.md src/bare-metal/aps/better-uart/driver.md +msgid "// Wait until there is room in the TX buffer.\n" +msgstr "// Wait until there is room in the TX buffer.\n" + +#: src/bare-metal/aps/uart.md +msgid "" +"// Safe because we know that the base address points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" +msgstr "" +"// Safe because we know that the base address points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" + +#: src/bare-metal/aps/uart.md src/bare-metal/aps/better-uart/driver.md +msgid "// Write to the TX buffer.\n" +msgstr "// Write to the TX buffer.\n" + +#: src/bare-metal/aps/uart.md src/bare-metal/aps/better-uart/driver.md +msgid "// Wait until the UART is no longer busy.\n" +msgstr "// Wait until the UART is no longer busy.\n" + +#: src/bare-metal/aps/uart.md msgid "" "Note that `Uart::new` is unsafe while the other methods are safe. This is " "because as long as the caller of `Uart::new` guarantees that its safety " @@ -14859,68 +18167,67 @@ msgid "" "it is always safe to call `write_byte` later because we can assume the " "necessary preconditions." msgstr "" +"請注意,`Uart::new` 並不安全,其他方法則是安全的。這是因為只要 `Uart::new` 的" +"呼叫端保證能滿足安全規定,也就是特定 UART 只有一個驅動程式例項,沒有其他項目" +"定義其位址空間的別名,那麼稍後呼叫 `write_byte` 一律是安全的,因為我們可以假" +"設必要的先決條件。" -#: src/bare-metal/aps/uart.md:60 +#: src/bare-metal/aps/uart.md msgid "" "We could have done it the other way around (making `new` safe but " "`write_byte` unsafe), but that would be much less convenient to use as every " "place that calls `write_byte` would need to reason about the safety" msgstr "" +"我們可以反過來操作,也就是讓 `new` 安全,而 `write_byte` 不安全,但這樣的使用" +"便利度低許多,因為每個呼叫 `write_byte` 的位置都需要分析安全性" -#: src/bare-metal/aps/uart.md:63 +#: src/bare-metal/aps/uart.md msgid "" "This is a common pattern for writing safe wrappers of unsafe code: moving " "the burden of proof for soundness from a large number of places to a smaller " "number of places." msgstr "" +"這是為不安全程式碼撰寫安全包裝函式的常見模式:將證明安全性的負擔從大量位置移" +"到少量位置。" -#: src/bare-metal/aps/uart/traits.md:1 +#: src/bare-metal/aps/uart/traits.md msgid "More traits" -msgstr "" +msgstr "其他特徵" -#: src/bare-metal/aps/uart/traits.md:3 +#: src/bare-metal/aps/uart/traits.md msgid "" "We derived the `Debug` trait. It would be useful to implement a few more " "traits too." -msgstr "" +msgstr "我們衍生了 `Debug` 特徵。實作多一點特徵也會有幫助。" -#: src/bare-metal/aps/uart/traits.md:5 +#: src/bare-metal/aps/uart/traits.md +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```rust,editable,compile_fail\n" -"use core::fmt::{self, Write};\n" -"\n" -"impl Write for Uart {\n" -" fn write_str(&mut self, s: &str) -> fmt::Result {\n" -" for c in s.as_bytes() {\n" -" self.write_byte(*c);\n" -" }\n" -" Ok(())\n" -" }\n" -"}\n" -"\n" "// Safe because it just contains a pointer to device memory, which can be\n" "// accessed from any context.\n" -"unsafe impl Send for Uart {}\n" -"```" msgstr "" +"// Safe because it just contains a pointer to device memory, which can be\n" +"// accessed from any context.\n" -#: src/bare-metal/aps/uart/traits.md:24 +#: src/bare-metal/aps/uart/traits.md msgid "" "Implementing `Write` lets us use the `write!` and `writeln!` macros with our " "`Uart` type." -msgstr "" +msgstr "實作 `Write` 即可搭配 `Uart` 型別使用 `write!` 和 `writeln!` 巨集。" -#: src/bare-metal/aps/uart/traits.md:25 +#: src/bare-metal/aps/uart/traits.md msgid "" "Run the example in QEMU with `make qemu_minimal` under `src/bare-metal/aps/" "examples`." msgstr "" +"使用 `src/bare-metal/aps/examples` 下的 `make qemu_minimal`,在 QEMU 中執行範" +"例。" -#: src/bare-metal/aps/better-uart.md:1 +#: src/bare-metal/aps/better-uart.md msgid "A better UART driver" -msgstr "" +msgstr "經改良的 UART 驅動程式" -#: src/bare-metal/aps/better-uart.md:3 +#: src/bare-metal/aps/better-uart.md msgid "" "The PL011 actually has [a bunch more registers](https://developer.arm.com/" "documentation/ddi0183/g/programmers-model/summary-of-registers), and adding " @@ -14928,260 +18235,220 @@ msgid "" "read. Plus, some of them are bit fields which would be nice to access in a " "structured way." msgstr "" +"PL011 實際上還有[許多暫存器](https://developer.arm.com/documentation/ddi0183/" +"g/programmers-model/summary-of-registers),若為了存取這些暫存器而將偏移值新增" +"至建構指標,不僅容易發生錯誤,還難以讀取。此外,部分暫存器是位元欄位,適合以" +"結構化方式存取。" -#: src/bare-metal/aps/better-uart.md:7 +#: src/bare-metal/aps/better-uart.md msgid "Offset" -msgstr "" +msgstr "偏移" -#: src/bare-metal/aps/better-uart.md:7 +#: src/bare-metal/aps/better-uart.md msgid "Register name" -msgstr "" +msgstr "暫存器名稱" -#: src/bare-metal/aps/better-uart.md:7 +#: src/bare-metal/aps/better-uart.md msgid "Width" -msgstr "" +msgstr "寬度" -#: src/bare-metal/aps/better-uart.md:9 +#: src/bare-metal/aps/better-uart.md msgid "0x00" -msgstr "" +msgstr "0x00" -#: src/bare-metal/aps/better-uart.md:9 +#: src/bare-metal/aps/better-uart.md msgid "DR" -msgstr "" +msgstr "DR" -#: src/bare-metal/aps/better-uart.md:9 +#: src/bare-metal/aps/better-uart.md msgid "12" -msgstr "" +msgstr "12" -#: src/bare-metal/aps/better-uart.md:10 +#: src/bare-metal/aps/better-uart.md msgid "0x04" -msgstr "" +msgstr "0x04" -#: src/bare-metal/aps/better-uart.md:10 +#: src/bare-metal/aps/better-uart.md msgid "RSR" -msgstr "" +msgstr "RSR" -#: src/bare-metal/aps/better-uart.md:10 -msgid "4" -msgstr "" - -#: src/bare-metal/aps/better-uart.md:11 +#: src/bare-metal/aps/better-uart.md msgid "0x18" -msgstr "" +msgstr "0x18" -#: src/bare-metal/aps/better-uart.md:11 +#: src/bare-metal/aps/better-uart.md msgid "FR" -msgstr "" +msgstr "FR" -#: src/bare-metal/aps/better-uart.md:11 +#: src/bare-metal/aps/better-uart.md msgid "9" -msgstr "" +msgstr "9" -#: src/bare-metal/aps/better-uart.md:12 +#: src/bare-metal/aps/better-uart.md msgid "0x20" -msgstr "" +msgstr "0x20" -#: src/bare-metal/aps/better-uart.md:12 +#: src/bare-metal/aps/better-uart.md msgid "ILPR" -msgstr "" +msgstr "ILPR" -#: src/bare-metal/aps/better-uart.md:12 src/bare-metal/aps/better-uart.md:15 -msgid "8" -msgstr "" - -#: src/bare-metal/aps/better-uart.md:13 +#: src/bare-metal/aps/better-uart.md msgid "0x24" -msgstr "" +msgstr "0x24" -#: src/bare-metal/aps/better-uart.md:13 +#: src/bare-metal/aps/better-uart.md msgid "IBRD" -msgstr "" +msgstr "IBRD" -#: src/bare-metal/aps/better-uart.md:13 src/bare-metal/aps/better-uart.md:16 +#: src/bare-metal/aps/better-uart.md msgid "16" -msgstr "" +msgstr "16" -#: src/bare-metal/aps/better-uart.md:14 +#: src/bare-metal/aps/better-uart.md msgid "0x28" -msgstr "" +msgstr "0x28" -#: src/bare-metal/aps/better-uart.md:14 +#: src/bare-metal/aps/better-uart.md msgid "FBRD" -msgstr "" +msgstr "FBRD" -#: src/bare-metal/aps/better-uart.md:14 src/bare-metal/aps/better-uart.md:17 -msgid "6" -msgstr "" - -#: src/bare-metal/aps/better-uart.md:15 +#: src/bare-metal/aps/better-uart.md msgid "0x2c" -msgstr "" +msgstr "0x2c" -#: src/bare-metal/aps/better-uart.md:15 +#: src/bare-metal/aps/better-uart.md msgid "LCR_H" -msgstr "" +msgstr "LCR_H" -#: src/bare-metal/aps/better-uart.md:16 +#: src/bare-metal/aps/better-uart.md msgid "0x30" -msgstr "" +msgstr "0x30" -#: src/bare-metal/aps/better-uart.md:16 +#: src/bare-metal/aps/better-uart.md msgid "CR" -msgstr "" +msgstr "CR" -#: src/bare-metal/aps/better-uart.md:17 +#: src/bare-metal/aps/better-uart.md msgid "0x34" -msgstr "" +msgstr "0x34" -#: src/bare-metal/aps/better-uart.md:17 +#: src/bare-metal/aps/better-uart.md msgid "IFLS" -msgstr "" +msgstr "IFLS" -#: src/bare-metal/aps/better-uart.md:18 +#: src/bare-metal/aps/better-uart.md msgid "0x38" -msgstr "" +msgstr "0x38" -#: src/bare-metal/aps/better-uart.md:18 +#: src/bare-metal/aps/better-uart.md msgid "IMSC" -msgstr "" +msgstr "IMSC" -#: src/bare-metal/aps/better-uart.md:18 src/bare-metal/aps/better-uart.md:19 -#: src/bare-metal/aps/better-uart.md:20 src/bare-metal/aps/better-uart.md:21 +#: src/bare-metal/aps/better-uart.md msgid "11" -msgstr "" +msgstr "11" -#: src/bare-metal/aps/better-uart.md:19 +#: src/bare-metal/aps/better-uart.md msgid "0x3c" -msgstr "" +msgstr "0x3c" -#: src/bare-metal/aps/better-uart.md:19 +#: src/bare-metal/aps/better-uart.md msgid "RIS" -msgstr "" +msgstr "RIS" -#: src/bare-metal/aps/better-uart.md:20 +#: src/bare-metal/aps/better-uart.md msgid "0x40" -msgstr "" +msgstr "0x40" -#: src/bare-metal/aps/better-uart.md:20 +#: src/bare-metal/aps/better-uart.md msgid "MIS" -msgstr "" +msgstr "MIS" -#: src/bare-metal/aps/better-uart.md:21 +#: src/bare-metal/aps/better-uart.md msgid "0x44" -msgstr "" +msgstr "0x44" -#: src/bare-metal/aps/better-uart.md:21 +#: src/bare-metal/aps/better-uart.md msgid "ICR" -msgstr "" +msgstr "ICR" -#: src/bare-metal/aps/better-uart.md:22 +#: src/bare-metal/aps/better-uart.md msgid "0x48" -msgstr "" +msgstr "0x48" -#: src/bare-metal/aps/better-uart.md:22 +#: src/bare-metal/aps/better-uart.md msgid "DMACR" -msgstr "" +msgstr "DMACR" -#: src/bare-metal/aps/better-uart.md:22 -msgid "3" -msgstr "" - -#: src/bare-metal/aps/better-uart.md:26 +#: src/bare-metal/aps/better-uart.md msgid "There are also some ID registers which have been omitted for brevity." -msgstr "" +msgstr "為求簡潔,還省略了一些 ID 暫存器。" -#: src/bare-metal/aps/better-uart/bitflags.md:3 +#: src/bare-metal/aps/better-uart/bitflags.md msgid "" "The [`bitflags`](https://crates.io/crates/bitflags) crate is useful for " "working with bitflags." msgstr "" +"[`bitflags`](https://crates.io/crates/bitflags) Crate 適合用於 Bitflags。" -#: src/bare-metal/aps/better-uart/bitflags.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"use bitflags::bitflags;\n" -"\n" -"bitflags! {\n" -" /// Flags from the UART flag register.\n" -" #[repr(transparent)]\n" -" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -" struct Flags: u16 {\n" -" /// Clear to send.\n" -" const CTS = 1 << 0;\n" -" /// Data set ready.\n" -" const DSR = 1 << 1;\n" -" /// Data carrier detect.\n" -" const DCD = 1 << 2;\n" -" /// UART busy transmitting data.\n" -" const BUSY = 1 << 3;\n" -" /// Receive FIFO is empty.\n" -" const RXFE = 1 << 4;\n" -" /// Transmit FIFO is full.\n" -" const TXFF = 1 << 5;\n" -" /// Receive FIFO is full.\n" -" const RXFF = 1 << 6;\n" -" /// Transmit FIFO is empty.\n" -" const TXFE = 1 << 7;\n" -" /// Ring indicator.\n" -" const RI = 1 << 8;\n" -" }\n" -"}\n" -"```" -msgstr "" +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Flags from the UART flag register.\n" +msgstr "/// Flags from the UART flag register.\n" -#: src/bare-metal/aps/better-uart/bitflags.md:37 +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Clear to send.\n" +msgstr "/// Clear to send.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Data set ready.\n" +msgstr "/// Data set ready.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Data carrier detect.\n" +msgstr "/// Data carrier detect.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// UART busy transmitting data.\n" +msgstr "/// UART busy transmitting data.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Receive FIFO is empty.\n" +msgstr "/// Receive FIFO is empty.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Transmit FIFO is full.\n" +msgstr "/// Transmit FIFO is full.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Receive FIFO is full.\n" +msgstr "/// Receive FIFO is full.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Transmit FIFO is empty.\n" +msgstr "/// Transmit FIFO is empty.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md +msgid "/// Ring indicator.\n" +msgstr "/// Ring indicator.\n" + +#: src/bare-metal/aps/better-uart/bitflags.md msgid "" "The `bitflags!` macro creates a newtype something like `Flags(u16)`, along " "with a bunch of method implementations to get and set flags." msgstr "" +"`bitflags!` 巨集會建立一個新型別 (例如 `Flags(u16)`),以及一系列取得及設定標" +"記的方法實作項目。" -#: src/bare-metal/aps/better-uart/registers.md:1 +#: src/bare-metal/aps/better-uart/registers.md msgid "Multiple registers" -msgstr "" +msgstr "多個暫存器" -#: src/bare-metal/aps/better-uart/registers.md:3 +#: src/bare-metal/aps/better-uart/registers.md msgid "" "We can use a struct to represent the memory layout of the UART's registers." -msgstr "" +msgstr "我們可以使用結構體來表示 UART 暫存器的記憶體布局。" -#: src/bare-metal/aps/better-uart/registers.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"#[repr(C, align(4))]\n" -"struct Registers {\n" -" dr: u16,\n" -" _reserved0: [u8; 2],\n" -" rsr: ReceiveStatus,\n" -" _reserved1: [u8; 19],\n" -" fr: Flags,\n" -" _reserved2: [u8; 6],\n" -" ilpr: u8,\n" -" _reserved3: [u8; 3],\n" -" ibrd: u16,\n" -" _reserved4: [u8; 2],\n" -" fbrd: u8,\n" -" _reserved5: [u8; 3],\n" -" lcr_h: u8,\n" -" _reserved6: [u8; 3],\n" -" cr: u16,\n" -" _reserved7: [u8; 3],\n" -" ifls: u8,\n" -" _reserved8: [u8; 3],\n" -" imsc: u16,\n" -" _reserved9: [u8; 2],\n" -" ris: u16,\n" -" _reserved10: [u8; 2],\n" -" mis: u16,\n" -" _reserved11: [u8; 2],\n" -" icr: u16,\n" -" _reserved12: [u8; 2],\n" -" dmacr: u8,\n" -" _reserved13: [u8; 3],\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/aps/better-uart/registers.md:41 +#: src/bare-metal/aps/better-uart/registers.md msgid "" "[`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-" "representation) tells the compiler to lay the struct fields out in order, " @@ -15189,452 +18456,383 @@ msgid "" "predictable layout, as default Rust representation allows the compiler to " "(among other things) reorder fields however it sees fit." msgstr "" +"[`#[repr(C)]`](https://doc.rust-lang.org/reference/type-layout.html#the-c-" +"representation) 會指示編譯器依序排列結構體欄位,遵循與 C 相同的規則。以確保結" +"構體具有可預測的布局,因為預設的 Rust 表示法允許編譯器依自身判斷重新排序欄位 " +"(和執行其他操作)。" -#: src/bare-metal/aps/better-uart/driver.md:3 +#: src/bare-metal/aps/better-uart/driver.md msgid "Now let's use the new `Registers` struct in our driver." -msgstr "" +msgstr "現在讓我們在驅動程式中使用新的 `Registers` 結構體。" -#: src/bare-metal/aps/better-uart/driver.md:5 +#: src/bare-metal/aps/better-uart/driver.md +msgid "/// Driver for a PL011 UART.\n" +msgstr "/// Driver for a PL011 UART.\n" + +#: src/bare-metal/aps/better-uart/driver.md msgid "" -"```rust,editable,compile_fail\n" -"/// Driver for a PL011 UART.\n" -"#[derive(Debug)]\n" -"pub struct Uart {\n" -" registers: *mut Registers,\n" -"}\n" -"\n" -"impl Uart {\n" -" /// Constructs a new instance of the UART driver for a PL011 device at " -"the\n" -" /// given base address.\n" -" ///\n" -" /// # Safety\n" -" ///\n" -" /// The given base address must point to the 8 MMIO control registers of " -"a\n" -" /// PL011 device, which must be mapped into the address space of the " -"process\n" -" /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u32) -> Self {\n" -" Self {\n" -" registers: base_address as *mut Registers,\n" -" }\n" -" }\n" -"\n" -" /// Writes a single byte to the UART.\n" -" pub fn write_byte(&self, byte: u8) {\n" -" // Wait until there is room in the TX buffer.\n" -" while self.read_flag_register().contains(Flags::TXFF) {}\n" -"\n" -" // Safe because we know that self.registers points to the control\n" +"// Safe because we know that self.registers points to the control\n" " // registers of a PL011 device which is appropriately mapped.\n" -" unsafe {\n" -" // Write to the TX buffer.\n" -" addr_of_mut!((*self.registers).dr).write_volatile(byte.into());\n" -" }\n" -"\n" -" // Wait until the UART is no longer busy.\n" -" while self.read_flag_register().contains(Flags::BUSY) {}\n" -" }\n" -"\n" -" /// Reads and returns a pending byte, or `None` if nothing has been " -"received.\n" -" pub fn read_byte(&self) -> Option {\n" -" if self.read_flag_register().contains(Flags::RXFE) {\n" -" None\n" -" } else {\n" -" let data = unsafe { addr_of!((*self.registers).dr)." -"read_volatile() };\n" -" // TODO: Check for error conditions in bits 8-11.\n" -" Some(data as u8)\n" -" }\n" -" }\n" -"\n" -" fn read_flag_register(&self) -> Flags {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe { addr_of!((*self.registers).fr).read_volatile() }\n" -" }\n" -"}\n" -"```" msgstr "" +"// Safe because we know that self.registers points to the control\n" +" // registers of a PL011 device which is appropriately mapped.\n" -#: src/bare-metal/aps/better-uart/driver.md:64 +#: src/bare-metal/aps/better-uart/driver.md +msgid "" +"/// Reads and returns a pending byte, or `None` if nothing has been\n" +" /// received.\n" +msgstr "" +"/// Reads and returns a pending byte, or `None` if nothing has been\n" +" /// received.\n" + +#: src/bare-metal/aps/better-uart/driver.md +msgid "// TODO: Check for error conditions in bits 8-11.\n" +msgstr "// TODO: Check for error conditions in bits 8-11.\n" + +#: src/bare-metal/aps/better-uart/driver.md msgid "" "Note the use of `addr_of!` / `addr_of_mut!` to get pointers to individual " "fields without creating an intermediate reference, which would be unsound." msgstr "" +"請注意,如果使用 `addr_of!`/`addr_of_mut!` 取得個別欄位的指標,而不建立中繼參" +"照,這種做法並不安全。" -#: src/bare-metal/aps/better-uart/using.md:1 -#: src/bare-metal/aps/logging/using.md:1 +#: src/bare-metal/aps/better-uart/using.md src/bare-metal/aps/logging/using.md msgid "Using it" -msgstr "" +msgstr "開始使用" -#: src/bare-metal/aps/better-uart/using.md:3 +#: src/bare-metal/aps/better-uart/using.md msgid "" "Let's write a small program using our driver to write to the serial console, " "and echo incoming bytes." -msgstr "" +msgstr "讓我們編寫一個小程式,使用驅動程式寫入序列控制台,並回應傳入的位元組。" -#: src/bare-metal/aps/better-uart/using.md:6 +#: src/bare-metal/aps/better-uart/using.md src/bare-metal/aps/logging/using.md +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Base address of the primary PL011 UART.\n" +msgstr "/// Base address of the primary PL011 UART.\n" + +#: src/bare-metal/aps/better-uart/using.md src/bare-metal/aps/logging/using.md +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"mod exceptions;\n" -"mod pl011;\n" -"\n" -"use crate::pl011::Uart;\n" -"use core::fmt::Write;\n" -"use core::panic::PanicInfo;\n" -"use log::error;\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"/// Base address of the primary PL011 UART.\n" -"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" -" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " -"device,\n" +"// Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 device,\n" " // and nothing else accesses that address range.\n" -" let mut uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -"\n" -" writeln!(uart, \"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\").unwrap();\n" -"\n" -" loop {\n" -" if let Some(b) = uart.read_byte() {\n" -" uart.write_byte(b);\n" -" match b {\n" -" b'\\r' => {\n" -" uart.write_byte(b'\\n');\n" -" }\n" -" b'q' => break,\n" -" _ => {}\n" -" }\n" -" }\n" -" }\n" -"\n" -" writeln!(uart, \"Bye!\").unwrap();\n" -" system_off::().unwrap();\n" -"}\n" -"```" msgstr "" +"// Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 device,\n" +" // and nothing else accesses that address range.\n" -#: src/bare-metal/aps/better-uart/using.md:51 +#: src/bare-metal/aps/better-uart/using.md src/bare-metal/aps/logging/using.md +msgid "\"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\"" +msgstr "\"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\"" + +#: src/bare-metal/aps/better-uart/using.md +msgid "b'\\r'" +msgstr "b'\\r'" + +#: src/bare-metal/aps/better-uart/using.md src/async/pitfalls/cancellation.md +msgid "b'\\n'" +msgstr "b'\\n'" + +#: src/bare-metal/aps/better-uart/using.md +msgid "b'q'" +msgstr "b'q'" + +#: src/bare-metal/aps/better-uart/using.md +msgid "\"Bye!\"" +msgstr "\"Bye!\"" + +#: src/bare-metal/aps/better-uart/using.md msgid "" "As in the [inline assembly](../inline-assembly.md) example, this `main` " "function is called from our entry point code in `entry.S`. See the speaker " "notes there for details." msgstr "" +"就像在[行內組語](../inline-assembly.md)範例中,系統會從 `entry.S` 的進入點程" +"式碼呼叫這個 `main` 函式。詳情請參閱演講者備忘稿。" -#: src/bare-metal/aps/better-uart/using.md:53 +#: src/bare-metal/aps/better-uart/using.md msgid "" "Run the example in QEMU with `make qemu` under `src/bare-metal/aps/examples`." msgstr "" +"使用 `src/bare-metal/aps/examples` 下的 `make qemu`,在 QEMU 中執行範例。" -#: src/bare-metal/aps/logging.md:3 +#: src/bare-metal/aps/logging.md msgid "" "It would be nice to be able to use the logging macros from the [`log`]" "(https://crates.io/crates/log) crate. We can do this by implementing the " "`Log` trait." msgstr "" +"建議使用 [`log`](https://crates.io/crates/log) Crate 中的記錄巨集。實作 " +"`Log` 特徵即可使用該項目。" -#: src/bare-metal/aps/logging.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use crate::pl011::Uart;\n" -"use core::fmt::Write;\n" -"use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};\n" -"use spin::mutex::SpinMutex;\n" -"\n" -"static LOGGER: Logger = Logger {\n" -" uart: SpinMutex::new(None),\n" -"};\n" -"\n" -"struct Logger {\n" -" uart: SpinMutex>,\n" -"}\n" -"\n" -"impl Log for Logger {\n" -" fn enabled(&self, _metadata: &Metadata) -> bool {\n" -" true\n" -" }\n" -"\n" -" fn log(&self, record: &Record) {\n" -" writeln!(\n" -" self.uart.lock().as_mut().unwrap(),\n" -" \"[{}] {}\",\n" -" record.level(),\n" -" record.args()\n" -" )\n" -" .unwrap();\n" -" }\n" -"\n" -" fn flush(&self) {}\n" -"}\n" -"\n" -"/// Initialises UART logger.\n" -"pub fn init(uart: Uart, max_level: LevelFilter) -> Result<(), " -"SetLoggerError> {\n" -" LOGGER.uart.lock().replace(uart);\n" -"\n" -" log::set_logger(&LOGGER)?;\n" -" log::set_max_level(max_level);\n" -" Ok(())\n" -"}\n" -"```" -msgstr "" +#: src/bare-metal/aps/logging.md +msgid "\"[{}] {}\"" +msgstr "\"[{}] {}\"" -#: src/bare-metal/aps/logging.md:50 +#: src/bare-metal/aps/logging.md +msgid "/// Initialises UART logger.\n" +msgstr "/// Initialises UART logger.\n" + +#: src/bare-metal/aps/logging.md msgid "" "The unwrap in `log` is safe because we initialise `LOGGER` before calling " "`set_logger`." msgstr "" +"在 `log` 中取消包裝很安全,因為在呼叫 `set_logger` 之前,我們會將 `LOGGER` 初" +"始化。" -#: src/bare-metal/aps/logging/using.md:3 +#: src/bare-metal/aps/logging/using.md msgid "We need to initialise the logger before we use it." -msgstr "" +msgstr "我們需要先初始化 Logger,才能使用 Logger。" -#: src/bare-metal/aps/logging/using.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"mod exceptions;\n" -"mod logger;\n" -"mod pl011;\n" -"\n" -"use crate::pl011::Uart;\n" -"use core::panic::PanicInfo;\n" -"use log::{error, info, LevelFilter};\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"/// Base address of the primary PL011 UART.\n" -"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" -" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " -"device,\n" -" // and nothing else accesses that address range.\n" -" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -" logger::init(uart, LevelFilter::Trace).unwrap();\n" -"\n" -" info!(\"main({x0:#x}, {x1:#x}, {x2:#x}, {x3:#x})\");\n" -"\n" -" assert_eq!(x1, 42);\n" -"\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[panic_handler]\n" -"fn panic(info: &PanicInfo) -> ! {\n" -" error!(\"{info}\");\n" -" system_off::().unwrap();\n" -" loop {}\n" -"}\n" -"```" -msgstr "" +#: src/bare-metal/aps/logging/using.md +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"{info}\"" +msgstr "\"{info}\"" -#: src/bare-metal/aps/logging/using.md:46 +#: src/bare-metal/aps/logging/using.md msgid "Note that our panic handler can now log details of panics." -msgstr "" +msgstr "請注意,恐慌處理常式現在可以記錄恐慌的詳細資料。" -#: src/bare-metal/aps/logging/using.md:47 +#: src/bare-metal/aps/logging/using.md msgid "" "Run the example in QEMU with `make qemu_logger` under `src/bare-metal/aps/" "examples`." msgstr "" +"使用 `src/bare-metal/aps/examples` 下的 `make qemu_logger`。在 QEMU 中執行範" +"例。" -#: src/bare-metal/aps/other-projects.md:3 +#: src/bare-metal/aps/exceptions.md +msgid "" +"AArch64 defines an exception vector table with 16 entries, for 4 types of " +"exceptions (synchronous, IRQ, FIQ, SError) from 4 states (current EL with " +"SP0, current EL with SPx, lower EL using AArch64, lower EL using AArch32). " +"We implement this in assembly to save volatile registers to the stack before " +"calling into Rust code:" +msgstr "" +"AArch64 定義了包含 16 個項目的例外狀況向量表,適用於 4 種狀態的 4 種例外狀" +"況,即同步、IRQ、FIQ、SError。4 種狀態則分別為目前 EL 搭配 SP0、目前 EL 搭配 " +"SPx、較低 EL 使用 AArch64 和較低 EL 使用 AArch32。這是在組語中實作,以便在呼" +"叫 Rust 程式碼之前,將揮發性暫存器儲存至堆疊:" + +#: src/bare-metal/aps/exceptions.md +msgid "EL is exception level; all our examples this afternoon run in EL1." +msgstr "EL 是指例外狀況層級,今天下午的所有範例都是在 EL1 執行。" + +#: src/bare-metal/aps/exceptions.md +msgid "" +"For simplicity we aren't distinguishing between SP0 and SPx for the current " +"EL exceptions, or between AArch32 and AArch64 for the lower EL exceptions." +msgstr "" +"為求簡單,我們不會針對目前 EL 例外狀況區分 SP0 和 SPx,也不會針對較低 EL 例外" +"狀況區分 AArch32 和 AArch64。" + +#: src/bare-metal/aps/exceptions.md +msgid "" +"For this example we just log the exception and power down, as we don't " +"expect any of them to actually happen." +msgstr "" +"在此範例中,我們只需記錄例外狀況並關機,因為我們並不預期會實際發生任何例外狀" +"況。" + +#: src/bare-metal/aps/exceptions.md +msgid "" +"We can think of exception handlers and our main execution context more or " +"less like different threads. [`Send` and `Sync`](../../concurrency/send-sync." +"md) will control what we can share between them, just like with threads. For " +"example, if we want to share some value between exception handlers and the " +"rest of the program, and it's `Send` but not `Sync`, then we'll need to wrap " +"it in something like a `Mutex` and put it in a static." +msgstr "" +"例外狀況處理常式和主執行環境,其實可以約略視為不同執行緒。[`Send` 和 `Sync`]" +"(../../concurrency/send-sync.md) 會控管可在它們之間分享的內容,就像執行緒一" +"樣。舉例來說,如要在例外狀況處理常式與程式其餘部分之間分享某個值,而且是 " +"`Send` (而非 `Sync`),我們就需要將該值包裝在 `Mutex` 等項目中並放入靜態項目。" + +#: src/bare-metal/aps/other-projects.md msgid "[oreboot](https://github.com/oreboot/oreboot)" -msgstr "" +msgstr "[oreboot](https://github.com/oreboot/oreboot)" -#: src/bare-metal/aps/other-projects.md:4 +#: src/bare-metal/aps/other-projects.md msgid "\"coreboot without the C\"" -msgstr "" +msgstr "「沒有 C 的 coreboot」" -#: src/bare-metal/aps/other-projects.md:5 +#: src/bare-metal/aps/other-projects.md msgid "Supports x86, aarch64 and RISC-V." -msgstr "" +msgstr "支援 x86、aarch64 和 RISC-V。" -#: src/bare-metal/aps/other-projects.md:6 +#: src/bare-metal/aps/other-projects.md msgid "Relies on LinuxBoot rather than having many drivers itself." -msgstr "" +msgstr "依賴 LinuxBoot,而非自身採用多個驅動程式。" -#: src/bare-metal/aps/other-projects.md:7 +#: src/bare-metal/aps/other-projects.md msgid "" "[Rust RaspberryPi OS tutorial](https://github.com/rust-embedded/rust-" "raspberrypi-OS-tutorials)" msgstr "" +"[Rust RaspberryPi OS 教學課程](https://github.com/rust-embedded/rust-" +"raspberrypi-OS-tutorials)" -#: src/bare-metal/aps/other-projects.md:8 +#: src/bare-metal/aps/other-projects.md msgid "" "Initialisation, UART driver, simple bootloader, JTAG, exception levels, " "exception handling, page tables" msgstr "" +"初始化、UART 驅動程式、簡易系統啟動載入程式、JTAG、例外狀況層級、例外狀況處" +"理、分頁表" -#: src/bare-metal/aps/other-projects.md:9 -msgid "Not all very well written, so beware." +#: src/bare-metal/aps/other-projects.md +msgid "" +"Some dodginess around cache maintenance and initialisation in Rust, not " +"necessarily a good example to copy for production code." msgstr "" +"Rust 中的快取維護和初始化存在疑慮,就正式版程式碼而言,不一定是值得複製的好範" +"例。" -#: src/bare-metal/aps/other-projects.md:10 +#: src/bare-metal/aps/other-projects.md msgid "[`cargo-call-stack`](https://crates.io/crates/cargo-call-stack)" -msgstr "" +msgstr "[`cargo-call-stack`](https://crates.io/crates/cargo-call-stack)" -#: src/bare-metal/aps/other-projects.md:11 +#: src/bare-metal/aps/other-projects.md msgid "Static analysis to determine maximum stack usage." -msgstr "" +msgstr "靜態分析,用來判斷最大堆疊用量。" -#: src/bare-metal/useful-crates.md:3 +#: src/bare-metal/aps/other-projects.md +msgid "" +"The RaspberryPi OS tutorial runs Rust code before the MMU and caches are " +"enabled. This will read and write memory (e.g. the stack). However:" +msgstr "" +"RaspberryPi OS 教學課程會在啟用 MMU 和快取之前,執行 Rust 程式碼。這會讀取及" +"寫入記憶體,例如堆疊。不過,請注意以下幾點:" + +#: src/bare-metal/aps/other-projects.md +msgid "" +"Without the MMU and cache, unaligned accesses will fault. It builds with " +"`aarch64-unknown-none` which sets `+strict-align` to prevent the compiler " +"generating unaligned accesses so it should be alright, but this is not " +"necessarily the case in general." +msgstr "" +"如果沒有 MMU 和快取,未對齊的存取會發生錯誤。建構時使用的是 `aarch64-unknown-" +"none`,這會設定 `+strict-align`,防止編譯器產生未對齊的存取,因此應該不會出" +"錯,但這不一定是一般情況。" + +#: src/bare-metal/aps/other-projects.md +msgid "" +"If it were running in a VM, this can lead to cache coherency issues. The " +"problem is that the VM is accessing memory directly with the cache disabled, " +"while the host has cacheable aliases to the same memory. Even if the host " +"doesn't explicitly access the memory, speculative accesses can lead to cache " +"fills, and then changes from one or the other will get lost. Again this is " +"alright in this particular case (running directly on the hardware with no " +"hypervisor), but isn't a good pattern in general." +msgstr "" +"如果是在 VM 中執行,可能會導致快取一致性問題。問題在於 VM 會在快取已停用時直" +"接存取記憶體,而主機具有相同記憶體的可快取別名。即使主機未明確存取記憶體,推" +"測存取行為仍可能導致快取填補,而存取之間的變更就會遺失。同樣地,這在本例中不" +"成問題 (直接在硬體上執行,沒有管理程序),但一般不建議採用這種模式。" + +#: src/bare-metal/useful-crates.md +msgid "Useful crates" +msgstr "實用的 Crate" + +#: src/bare-metal/useful-crates.md msgid "" "We'll go over a few crates which solve some common problems in bare-metal " "programming." -msgstr "" +msgstr "以下將介紹幾個 Crate,可用來解決一些裸機程式設計的常見問題。" -#: src/bare-metal/useful-crates/zerocopy.md:1 -msgid "`zerocopy`" -msgstr "" - -#: src/bare-metal/useful-crates/zerocopy.md:3 +#: src/bare-metal/useful-crates/zerocopy.md msgid "" "The [`zerocopy`](https://docs.rs/zerocopy/) crate (from Fuchsia) provides " "traits and macros for safely converting between byte sequences and other " "types." msgstr "" +"[`zerocopy`](https://docs.rs/zerocopy/) Crate (來自 Fuchsia) 提供特徵和巨集," +"可在位元組序列和其他型別之間安全地轉換。" -#: src/bare-metal/useful-crates/zerocopy.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use zerocopy::AsBytes;\n" -"\n" -"#[repr(u32)]\n" -"#[derive(AsBytes, Debug, Default)]\n" -"enum RequestType {\n" -" #[default]\n" -" In = 0,\n" -" Out = 1,\n" -" Flush = 4,\n" -"}\n" -"\n" -"#[repr(C)]\n" -"#[derive(AsBytes, Debug, Default)]\n" -"struct VirtioBlockRequest {\n" -" request_type: RequestType,\n" -" reserved: u32,\n" -" sector: u64,\n" -"}\n" -"\n" -"fn main() {\n" -" let request = VirtioBlockRequest {\n" -" request_type: RequestType::Flush,\n" -" sector: 42,\n" -" ..Default::default()\n" -" };\n" -"\n" -" assert_eq!(\n" -" request.as_bytes(),\n" -" &[4, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0, 0, 0, 0, 0, 0]\n" -" );\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/useful-crates/zerocopy.md:40 +#: src/bare-metal/useful-crates/zerocopy.md msgid "" "This is not suitable for MMIO (as it doesn't use volatile reads and writes), " "but can be useful for working with structures shared with hardware e.g. by " "DMA, or sent over some external interface." msgstr "" +"這不適合 MMIO (因為並非採用揮發性讀取和寫入方法),但很適合搭配使用與硬體共用" +"的結構 (例如藉由 DMA),或透過外部介面傳送的結構。" -#: src/bare-metal/useful-crates/zerocopy.md:45 +#: src/bare-metal/useful-crates/zerocopy.md msgid "" "`FromBytes` can be implemented for types for which any byte pattern is " "valid, and so can safely be converted from an untrusted sequence of bytes." msgstr "" +"`FromBytes` 可針對任何位元組模式有效的型別實作,因此可從不受信任的位元組序列" +"安全地完成轉換。" -#: src/bare-metal/useful-crates/zerocopy.md:47 +#: src/bare-metal/useful-crates/zerocopy.md msgid "" "Attempting to derive `FromBytes` for these types would fail, because " "`RequestType` doesn't use all possible u32 values as discriminants, so not " "all byte patterns are valid." msgstr "" +"嘗試衍生這些型別的 `FromBytes` 會失敗,因為 `RequestType` 不會使用所有可能的 " +"u32 值做為判別值,所以並非所有位元組模式都有效。" -#: src/bare-metal/useful-crates/zerocopy.md:49 +#: src/bare-metal/useful-crates/zerocopy.md msgid "" "`zerocopy::byteorder` has types for byte-order aware numeric primitives." -msgstr "" +msgstr "`zerocopy::byteorder` 的型別適用於瞭解位元組順序的數值基元。" -#: src/bare-metal/useful-crates/zerocopy.md:50 +#: src/bare-metal/useful-crates/zerocopy.md msgid "" "Run the example with `cargo run` under `src/bare-metal/useful-crates/" "zerocopy-example/`. (It won't run in the Playground because of the crate " "dependency.)" msgstr "" +"使用 `src/bare-metal/useful-crates/zerocopy-example/` 下的 `cargo run` 執行範" +"例 (在 Playground 中,範例會因為 Crate 依附元件而無法執行)。" -#: src/bare-metal/useful-crates/aarch64-paging.md:1 -msgid "`aarch64-paging`" -msgstr "" - -#: src/bare-metal/useful-crates/aarch64-paging.md:3 +#: src/bare-metal/useful-crates/aarch64-paging.md msgid "" "The [`aarch64-paging`](https://crates.io/crates/aarch64-paging) crate lets " "you create page tables according to the AArch64 Virtual Memory System " "Architecture." msgstr "" +"[`aarch64-paging`](https://crates.io/crates/aarch64-paging) Crate 可用來根據 " +"AArch64 虛擬記憶體系統架構,建立分頁表。" -#: src/bare-metal/useful-crates/aarch64-paging.md:6 -msgid "" -"```rust,editable,compile_fail\n" -"use aarch64_paging::{\n" -" idmap::IdMap,\n" -" paging::{Attributes, MemoryRegion},\n" -"};\n" -"\n" -"const ASID: usize = 1;\n" -"const ROOT_LEVEL: usize = 1;\n" -"\n" -"// Create a new page table with identity mapping.\n" -"let mut idmap = IdMap::new(ASID, ROOT_LEVEL);\n" -"// Map a 2 MiB region of memory as read-only.\n" -"idmap.map_range(\n" -" &MemoryRegion::new(0x80200000, 0x80400000),\n" -" Attributes::NORMAL | Attributes::NON_GLOBAL | Attributes::READ_ONLY,\n" -").unwrap();\n" -"// Set `TTBR0_EL1` to activate the page table.\n" -"idmap.activate();\n" -"```" -msgstr "" +#: src/bare-metal/useful-crates/aarch64-paging.md +msgid "// Create a new page table with identity mapping.\n" +msgstr "// Create a new page table with identity mapping.\n" -#: src/bare-metal/useful-crates/aarch64-paging.md:28 +#: src/bare-metal/useful-crates/aarch64-paging.md +msgid "// Map a 2 MiB region of memory as read-only.\n" +msgstr "// Map a 2 MiB region of memory as read-only.\n" + +#: src/bare-metal/useful-crates/aarch64-paging.md +msgid "// Set `TTBR0_EL1` to activate the page table.\n" +msgstr "// Set `TTBR0_EL1` to activate the page table.\n" + +#: src/bare-metal/useful-crates/aarch64-paging.md msgid "" "For now it only supports EL1, but support for other exception levels should " "be straightforward to add." -msgstr "" +msgstr "目前僅支援 EL1,但應該很容易新增其他例外狀況層級的支援功能。" -#: src/bare-metal/useful-crates/aarch64-paging.md:30 +#: src/bare-metal/useful-crates/aarch64-paging.md msgid "" "This is used in Android for the [Protected VM Firmware](https://cs.android." "com/android/platform/superproject/+/master:packages/modules/Virtualization/" "pvmfw/)." msgstr "" +"這是用於 Android 中的[受保護 VM 韌體](https://cs.android.com/android/" +"platform/superproject/+/master:packages/modules/Virtualization/pvmfw/)。" -#: src/bare-metal/useful-crates/aarch64-paging.md:31 +#: src/bare-metal/useful-crates/aarch64-paging.md msgid "" "There's no easy way to run this example, as it needs to run on real hardware " "or under QEMU." -msgstr "" +msgstr "執行這個範例並不容易,因為需要在實際硬體上執行,或是使用 QEMU。" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:1 -msgid "`buddy_system_allocator`" -msgstr "" - -#: src/bare-metal/useful-crates/buddy_system_allocator.md:3 +#: src/bare-metal/useful-crates/buddy_system_allocator.md msgid "" "[`buddy_system_allocator`](https://crates.io/crates/buddy_system_allocator) " "is a third-party crate implementing a basic buddy system allocator. It can " @@ -15645,42 +18843,27 @@ msgid "" "allocating other address space. For example, we might want to allocate MMIO " "space for PCI BARs:" msgstr "" +"[`buddy_system_allocator`](https://crates.io/crates/buddy_system_allocator) " +"是實作基本夥伴系統分配器的第三方 Crate。這可供 [`LockedHeap`](https://docs." +"rs/buddy_system_allocator/0.9.0/buddy_system_allocator/struct.LockedHeap." +"html) 實作 [`GlobalAlloc`](https://doc.rust-lang.org/core/alloc/trait." +"GlobalAlloc.html),以便使用標準 `alloc` Crate,如[先前](../alloc.md)所見,或" +"用來分配其他位址空間。例如,我們可能會想針對 PCI BAR 分配 MMIO 空間:" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:8 -msgid "" -"```rust,editable,compile_fail\n" -"use buddy_system_allocator::FrameAllocator;\n" -"use core::alloc::Layout;\n" -"\n" -"fn main() {\n" -" let mut allocator = FrameAllocator::<32>::new();\n" -" allocator.add_frame(0x200_0000, 0x400_0000);\n" -"\n" -" let layout = Layout::from_size_align(0x100, 0x100).unwrap();\n" -" let bar = allocator\n" -" .alloc_aligned(layout)\n" -" .expect(\"Failed to allocate 0x100 byte MMIO region\");\n" -" println!(\"Allocated 0x100 byte MMIO region at {:#x}\", bar);\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/useful-crates/buddy_system_allocator.md:26 +#: src/bare-metal/useful-crates/buddy_system_allocator.md msgid "PCI BARs always have alignment equal to their size." -msgstr "" +msgstr "PCI BAR 的對齊情形一律會等於其大小。" -#: src/bare-metal/useful-crates/buddy_system_allocator.md:27 +#: src/bare-metal/useful-crates/buddy_system_allocator.md msgid "" "Run the example with `cargo run` under `src/bare-metal/useful-crates/" "allocator-example/`. (It won't run in the Playground because of the crate " "dependency.)" msgstr "" +"使用 `src/bare-metal/useful-crates/allocator-example/` 下的 `cargo run` 執行" +"範例 (在 Playground 中,範例會因為 Crate 依附元件而無法執行)。" -#: src/bare-metal/useful-crates/tinyvec.md:1 -msgid "`tinyvec`" -msgstr "" - -#: src/bare-metal/useful-crates/tinyvec.md:3 +#: src/bare-metal/useful-crates/tinyvec.md msgid "" "Sometimes you want something which can be resized like a `Vec`, but without " "heap allocation. [`tinyvec`](https://crates.io/crates/tinyvec) provides " @@ -15688,1280 +18871,427 @@ msgid "" "allocated or on the stack, which keeps track of how many elements are used " "and panics if you try to use more than are allocated." msgstr "" +"有時候,您會希望有項目可以像 `Vec` 一樣調整大小,但沒有堆積分配量。" +"[`tinyvec`](https://crates.io/crates/tinyvec) 提供這項機制:這個向量由陣列或" +"切片支援,能以靜態方式分配或置於堆疊,進而追蹤元素用量,以及因您嘗試使用的量" +"超出分配量所導致的恐慌。" -#: src/bare-metal/useful-crates/tinyvec.md:8 -msgid "" -"```rust,editable,compile_fail\n" -"use tinyvec::{array_vec, ArrayVec};\n" -"\n" -"fn main() {\n" -" let mut numbers: ArrayVec<[u32; 5]> = array_vec!(42, 66);\n" -" println!(\"{numbers:?}\");\n" -" numbers.push(7);\n" -" println!(\"{numbers:?}\");\n" -" numbers.remove(1);\n" -" println!(\"{numbers:?}\");\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/useful-crates/tinyvec.md:23 +#: src/bare-metal/useful-crates/tinyvec.md msgid "" "`tinyvec` requires that the element type implement `Default` for " "initialisation." -msgstr "" +msgstr "為初始化,`tinyvec` 規定元素型別須實作 `Default`。" -#: src/bare-metal/useful-crates/tinyvec.md:24 +#: src/bare-metal/useful-crates/tinyvec.md msgid "" "The Rust Playground includes `tinyvec`, so this example will run fine inline." -msgstr "" +msgstr "Rust Playground 包含 `tinyvec`,因此這個範例可在行內執行。" -#: src/bare-metal/useful-crates/spin.md:1 -msgid "`spin`" -msgstr "" - -#: src/bare-metal/useful-crates/spin.md:3 +#: src/bare-metal/useful-crates/spin.md msgid "" "`std::sync::Mutex` and the other synchronisation primitives from `std::sync` " "are not available in `core` or `alloc`. How can we manage synchronisation or " "interior mutability, such as for sharing state between different CPUs?" msgstr "" +"`std::sync::Mutex` 和其他來自 `std::sync` 的同步基元,都無法用於 `core` 或 " +"`alloc`。我們能如何管理同步處理作業或內部可變動性 (例如為了在不同 CPU 之間共" +"用狀態) 呢?" -#: src/bare-metal/useful-crates/spin.md:7 +#: src/bare-metal/useful-crates/spin.md msgid "" "The [`spin`](https://crates.io/crates/spin) crate provides spinlock-based " "equivalents of many of these primitives." msgstr "" +"[`spin`](https://crates.io/crates/spin) Crate 針對許多這類基元,提供以自旋鎖" +"為基礎的同等項目。" -#: src/bare-metal/useful-crates/spin.md:9 -msgid "" -"```rust,editable,compile_fail\n" -"use spin::mutex::SpinMutex;\n" -"\n" -"static counter: SpinMutex = SpinMutex::new(0);\n" -"\n" -"fn main() {\n" -" println!(\"count: {}\", counter.lock());\n" -" *counter.lock() += 2;\n" -" println!(\"count: {}\", counter.lock());\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/useful-crates/spin.md:23 +#: src/bare-metal/useful-crates/spin.md msgid "Be careful to avoid deadlock if you take locks in interrupt handlers." -msgstr "" +msgstr "如果在中斷處理常式使用了鎖,請務必小心避免死結。" -#: src/bare-metal/useful-crates/spin.md:24 +#: src/bare-metal/useful-crates/spin.md msgid "" "`spin` also has a ticket lock mutex implementation; equivalents of `RwLock`, " -"`Barrier` and `Once` from `std::sync`; and `Lazy` for lazy initialisation." +"`Barrier` and `Once` from `std::sync`; and `Lazy` for lazy initialisation." msgstr "" +"`spin` 也具備排號自旋鎖互斥實作項目;`std::sync` 中 `RwLock`、`Barrier` 和 " +"`Once` 的同等項目;以及用於延遲初始化的 `Lazy`。" -#: src/bare-metal/useful-crates/spin.md:26 +#: src/bare-metal/useful-crates/spin.md msgid "" "The [`once_cell`](https://crates.io/crates/once_cell) crate also has some " "useful types for late initialisation with a slightly different approach to " "`spin::once::Once`." msgstr "" +"[`once_cell`](https://crates.io/crates/once_cell) Crate 也具備一些實用型別," +"適合用於晚期初始化,與 `spin::once::Once` 的做法略有不同。" -#: src/bare-metal/useful-crates/spin.md:28 +#: src/bare-metal/useful-crates/spin.md msgid "" "The Rust Playground includes `spin`, so this example will run fine inline." -msgstr "" +msgstr "Rust Playground 包含 `spin`,因此這個範例可在行內執行。" -#: src/bare-metal/android.md:3 +#: src/bare-metal/android.md msgid "" "To build a bare-metal Rust binary in AOSP, you need to use a " "`rust_ffi_static` Soong rule to build your Rust code, then a `cc_binary` " "with a linker script to produce the binary itself, and then a `raw_binary` " "to convert the ELF to a raw binary ready to be run." msgstr "" +"如要在 Android 開放原始碼計畫中建構 Rust 裸機開發二進位檔,您需要使用 " +"`rust_ffi_static` Soong 規則建構 Rust 程式碼,接著使用具有連接器指令碼的 " +"`cc_binary` 產生二進位檔,並以 `raw_binary` 將 ELF 轉換為準備好執行的原始二進" +"位檔。" -#: src/bare-metal/android.md:7 -msgid "" -"```soong\n" -"rust_ffi_static {\n" -" name: \"libvmbase_example\",\n" -" defaults: [\"vmbase_ffi_defaults\"],\n" -" crate_name: \"vmbase_example\",\n" -" srcs: [\"src/main.rs\"],\n" -" rustlibs: [\n" -" \"libvmbase\",\n" -" ],\n" -"}\n" -"\n" -"cc_binary {\n" -" name: \"vmbase_example\",\n" -" defaults: [\"vmbase_elf_defaults\"],\n" -" srcs: [\n" -" \"idmap.S\",\n" -" ],\n" -" static_libs: [\n" -" \"libvmbase_example\",\n" -" ],\n" -" linker_scripts: [\n" -" \"image.ld\",\n" -" \":vmbase_sections\",\n" -" ],\n" -"}\n" -"\n" -"raw_binary {\n" -" name: \"vmbase_example_bin\",\n" -" stem: \"vmbase_example.bin\",\n" -" src: \":vmbase_example\",\n" -" enabled: false,\n" -" target: {\n" -" android_arm64: {\n" -" enabled: true,\n" -" },\n" -" },\n" -"}\n" -"```" -msgstr "" +#: src/bare-metal/android/vmbase.md +msgid "vmbase" +msgstr "vmbase" -#: src/bare-metal/android/vmbase.md:3 +#: src/bare-metal/android/vmbase.md msgid "" "For VMs running under crosvm on aarch64, the [vmbase](https://android." "googlesource.com/platform/packages/modules/Virtualization/+/refs/heads/" "master/vmbase/) library provides a linker script and useful defaults for the " "build rules, along with an entry point, UART console logging and more." msgstr "" +"針對在 aarch64 的 crosvm 下運作的 VM,[vmbase](https://android.googlesource." +"com/platform/packages/modules/Virtualization/+/refs/heads/master/vmbase/) 程" +"式庫提供連接器指令碼和實用的建構規則預設值,以及進入點、UART 控制台記錄等。" -#: src/bare-metal/android/vmbase.md:6 -msgid "" -"```rust,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"use vmbase::{main, println};\n" -"\n" -"main!(main);\n" -"\n" -"pub fn main(arg0: u64, arg1: u64, arg2: u64, arg3: u64) {\n" -" println!(\"Hello world\");\n" -"}\n" -"```" -msgstr "" - -#: src/bare-metal/android/vmbase.md:21 +#: src/bare-metal/android/vmbase.md msgid "" "The `main!` macro marks your main function, to be called from the `vmbase` " "entry point." -msgstr "" +msgstr "`main!` 巨集會標記主函式,方便從 `vmbase` 進入點呼叫。" -#: src/bare-metal/android/vmbase.md:22 +#: src/bare-metal/android/vmbase.md msgid "" "The `vmbase` entry point handles console initialisation, and issues a " "PSCI_SYSTEM_OFF to shutdown the VM if your main function returns." msgstr "" +"`vmbase` 進入點會處理控制台初始化作業,並在主函式傳回時發出 PSCI_SYSTEM_OFF " +"來關閉 VM。" -#: src/exercises/bare-metal/afternoon.md:3 +#: src/exercises/bare-metal/afternoon.md msgid "We will write a driver for the PL031 real-time clock device." -msgstr "" +msgstr "我們將為 PL031 即時時鐘裝置編寫驅動程式。" -#: src/exercises/bare-metal/rtc.md:1 -#: src/exercises/bare-metal/solutions-afternoon.md:3 +#: src/exercises/bare-metal/afternoon.md src/exercises/concurrency/afternoon.md +msgid "" +"After looking at the exercises, you can look at the [solutions](solutions-" +"afternoon.md) provided." +msgstr "完成練習後,您可以看看我們提供的[解決方案](solutions-afternoon.md)。" + +#: src/exercises/bare-metal/rtc.md +#: src/exercises/bare-metal/solutions-afternoon.md msgid "RTC driver" -msgstr "" +msgstr "RTC 驅動程式" -#: src/exercises/bare-metal/rtc.md:3 +#: src/exercises/bare-metal/rtc.md msgid "" "The QEMU aarch64 virt machine has a [PL031](https://developer.arm.com/" "documentation/ddi0224/c) real-time clock at 0x9010000. For this exercise, " "you should write a driver for it." msgstr "" +"QEMU aarch64 虛擬機器的 [PL031](https://developer.arm.com/documentation/" +"ddi0224/c) 即時時鐘位於 0x9010000。在這個練習中,您應為該時鐘編寫驅動程式。" -#: src/exercises/bare-metal/rtc.md:6 +#: src/exercises/bare-metal/rtc.md msgid "" "Use it to print the current time to the serial console. You can use the " "[`chrono`](https://crates.io/crates/chrono) crate for date/time formatting." msgstr "" +"使用該時鐘將目前時間顯示至序列控制台。您可以使用 [`chrono`](https://crates." +"io/crates/chrono) Crate 設定日期/時間格式。" -#: src/exercises/bare-metal/rtc.md:8 +#: src/exercises/bare-metal/rtc.md msgid "" "Use the match register and raw interrupt status to busy-wait until a given " "time, e.g. 3 seconds in the future. (Call [`core::hint::spin_loop`](https://" "doc.rust-lang.org/core/hint/fn.spin_loop.html) inside the loop.)" msgstr "" +"使用比對暫存器和原始中斷狀態,忙碌等待至指定時間,例如未來 3 秒 (呼叫迴圈中" +"的 [`core::hint::spin_loop`](https://doc.rust-lang.org/core/hint/fn." +"spin_loop.html))。" -#: src/exercises/bare-metal/rtc.md:10 +#: src/exercises/bare-metal/rtc.md msgid "" "_Extension if you have time:_ Enable and handle the interrupt generated by " "the RTC match. You can use the driver provided in the [`arm-gic`](https://" "docs.rs/arm-gic/) crate to configure the Arm Generic Interrupt Controller." msgstr "" +"擴充功能 (如有時間):啟用並處理因 RTC 比對而產生的中斷情形。您可以使用 [`arm-" +"gic`](https://docs.rs/arm-gic/) Crate 中提供的驅動程式,設定 Arm 泛型中斷控制" +"器。" -#: src/exercises/bare-metal/rtc.md:12 +#: src/exercises/bare-metal/rtc.md msgid "Use the RTC interrupt, which is wired to the GIC as `IntId::spi(2)`." -msgstr "" +msgstr "使用做為 `IntId::spi(2)` 有線連結至 GIC 的 RTC 中斷。" -#: src/exercises/bare-metal/rtc.md:13 +#: src/exercises/bare-metal/rtc.md msgid "" "Once the interrupt is enabled, you can put the core to sleep via `arm_gic::" "wfi()`, which will cause the core to sleep until it receives an interrupt." msgstr "" +"啟用中斷功能後,您可以透過 `arm_gic::wfi()` 將核心設為休眠,這樣核心就會進入" +"休眠狀態,直到遭中斷為止。" -#: src/exercises/bare-metal/rtc.md:16 +#: src/exercises/bare-metal/rtc.md msgid "" "Download the [exercise template](../../comprehensive-rust-exercises.zip) and " "look in the `rtc` directory for the following files." msgstr "" +"請下載[練習範本](../../comprehensive-rust-exercises.zip),並在 `rtc` 目錄中查" +"看下列檔案。" -#: src/exercises/bare-metal/rtc.md:23 +#: src/exercises/bare-metal/rtc.md msgid "" -"```rust,compile_fail\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"mod exceptions;\n" -"mod logger;\n" -"mod pl011;\n" -"\n" -"use crate::pl011::Uart;\n" -"use arm_gic::gicv3::GicV3;\n" -"use core::panic::PanicInfo;\n" -"use log::{error, info, trace, LevelFilter};\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"/// Base addresses of the GICv3.\n" -"const GICD_BASE_ADDRESS: *mut u64 = 0x800_0000 as _;\n" -"const GICR_BASE_ADDRESS: *mut u64 = 0x80A_0000 as _;\n" -"\n" -"/// Base address of the primary PL011 UART.\n" -"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" -" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " -"device,\n" -" // and nothing else accesses that address range.\n" -" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -" logger::init(uart, LevelFilter::Trace).unwrap();\n" -"\n" -" info!(\"main({:#x}, {:#x}, {:#x}, {:#x})\", x0, x1, x2, x3);\n" -"\n" -" // Safe because `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the " -"base\n" +"_src/exceptions.rs_ (you should only need to change this for the 3rd part of " +"the exercise):" +msgstr "src/exceptions.rs (您應該只需為練習的第 3 部分變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_src/logger.rs_ (you shouldn't need to change this):" +msgstr "src/logger.rs (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_src/pl011.rs_ (you shouldn't need to change this):" +msgstr "src/pl011.rs (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_build.rs_ (you shouldn't need to change this):" +msgstr "build.rs (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_entry.S_ (you shouldn't need to change this):" +msgstr "entry.S (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_exceptions.S_ (you shouldn't need to change this):" +msgstr "exceptions.S (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_idmap.S_ (you shouldn't need to change this):" +msgstr "idmap.S (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_image.ld_ (you shouldn't need to change this):" +msgstr "image.ld (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "_Makefile_ (you shouldn't need to change this):" +msgstr "Makefile (您應該不需要變更此項目):" + +#: src/exercises/bare-metal/rtc.md +msgid "Run the code in QEMU with `make qemu`." +msgstr "使用 `make qemu`,在 QEMU 中執行程式碼。" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "Bare Metal Rust Afternoon" +msgstr "Rust 裸機開發:下午" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "([back to exercise](rtc.md))" +msgstr "([返回練習](rtc.md))" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "_main.rs_:" +msgstr "_main.rs_:" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Base addresses of the GICv3.\n" +msgstr "/// Base addresses of the GICv3.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Base address of the PL031 RTC.\n" +msgstr "/// Base address of the PL031 RTC.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// The IRQ used by the PL031 RTC.\n" +msgstr "/// The IRQ used by the PL031 RTC.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"main({:#x}, {:#x}, {:#x}, {:#x})\"" +msgstr "\"main({:#x}, {:#x}, {:#x}, {:#x})\"" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "" +"// Safe because `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the base\n" " // addresses of a GICv3 distributor and redistributor respectively, and\n" " // nothing else accesses those address ranges.\n" -" let mut gic = unsafe { GicV3::new(GICD_BASE_ADDRESS, " -"GICR_BASE_ADDRESS) };\n" -" gic.setup();\n" -"\n" -" // TODO: Create instance of RTC driver and print current time.\n" -"\n" -" // TODO: Wait for 3 seconds.\n" -"\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[panic_handler]\n" -"fn panic(info: &PanicInfo) -> ! {\n" -" error!(\"{info}\");\n" -" system_off::().unwrap();\n" -" loop {}\n" -"}\n" -"```" msgstr "" +"// Safe because `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the base\n" +" // addresses of a GICv3 distributor and redistributor respectively, and\n" +" // nothing else accesses those address ranges.\n" -#: src/exercises/bare-metal/rtc.md:75 +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"`src/exceptions.rs` (you should only need to change this for the 3rd part of " -"the exercise):" +"// Safe because `PL031_BASE_ADDRESS` is the base address of a PL031 device,\n" +" // and nothing else accesses that address range.\n" msgstr "" +"// Safe because `PL031_BASE_ADDRESS` is the base address of a PL031 device,\n" +" // and nothing else accesses that address range.\n" -#: src/exercises/bare-metal/rtc.md:79 +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"RTC: {time}\"" +msgstr "\"RTC: {time}\"" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "// Wait for 3 seconds, without interrupts.\n" +msgstr "// Wait for 3 seconds, without interrupts.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"Waiting for {}\"" +msgstr "\"Waiting for {}\"" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"matched={}, interrupt_pending={}\"" +msgstr "\"matched={}, interrupt_pending={}\"" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "\"Finished waiting\"" +msgstr "\"Finished waiting\"" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "// Wait another 3 seconds for an interrupt.\n" +msgstr "// Wait another 3 seconds for an interrupt.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +#, fuzzy +msgid "_pl031.rs_:" +msgstr "_pl031.rs_:" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Data register\n" +msgstr "/// Data register\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Match register\n" +msgstr "/// Match register\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Load register\n" +msgstr "/// Load register\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Control register\n" +msgstr "/// Control register\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Interrupt Mask Set or Clear register\n" +msgstr "/// Interrupt Mask Set or Clear register\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Raw Interrupt Status\n" +msgstr "/// Raw Interrupt Status\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Masked Interrupt Status\n" +msgstr "/// Masked Interrupt Status\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Interrupt Clear Register\n" +msgstr "/// Interrupt Clear Register\n" + +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Driver for a PL031 real-time clock.\n" +msgstr "/// Driver for a PL031 real-time clock.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"use arm_gic::gicv3::GicV3;\n" -"use log::{error, info, trace};\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn sync_exception_current(_elr: u64, _spsr: u64) {\n" -" error!(\"sync_exception_current\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn irq_current(_elr: u64, _spsr: u64) {\n" -" trace!(\"irq_current\");\n" -" let intid = GicV3::get_and_acknowledge_interrupt().expect(\"No pending " -"interrupt\");\n" -" info!(\"IRQ {intid:?}\");\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn fiq_current(_elr: u64, _spsr: u64) {\n" -" error!(\"fiq_current\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn serr_current(_elr: u64, _spsr: u64) {\n" -" error!(\"serr_current\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn sync_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"sync_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn irq_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"irq_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn fiq_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"fiq_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[no_mangle]\n" -"extern \"C\" fn serr_lower(_elr: u64, _spsr: u64) {\n" -" error!(\"serr_lower\");\n" -" system_off::().unwrap();\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:149 -msgid "`src/logger.rs` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:153 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: main\n" -"use crate::pl011::Uart;\n" -"use core::fmt::Write;\n" -"use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};\n" -"use spin::mutex::SpinMutex;\n" -"\n" -"static LOGGER: Logger = Logger {\n" -" uart: SpinMutex::new(None),\n" -"};\n" -"\n" -"struct Logger {\n" -" uart: SpinMutex>,\n" -"}\n" -"\n" -"impl Log for Logger {\n" -" fn enabled(&self, _metadata: &Metadata) -> bool {\n" -" true\n" -" }\n" -"\n" -" fn log(&self, record: &Record) {\n" -" writeln!(\n" -" self.uart.lock().as_mut().unwrap(),\n" -" \"[{}] {}\",\n" -" record.level(),\n" -" record.args()\n" -" )\n" -" .unwrap();\n" -" }\n" -"\n" -" fn flush(&self) {}\n" -"}\n" -"\n" -"/// Initialises UART logger.\n" -"pub fn init(uart: Uart, max_level: LevelFilter) -> Result<(), " -"SetLoggerError> {\n" -" LOGGER.uart.lock().replace(uart);\n" -"\n" -" log::set_logger(&LOGGER)?;\n" -" log::set_max_level(max_level);\n" -" Ok(())\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:210 -msgid "`src/pl011.rs` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:214 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"#![allow(unused)]\n" -"\n" -"use core::fmt::{self, Write};\n" -"use core::ptr::{addr_of, addr_of_mut};\n" -"\n" -"// ANCHOR: Flags\n" -"use bitflags::bitflags;\n" -"\n" -"bitflags! {\n" -" /// Flags from the UART flag register.\n" -" #[repr(transparent)]\n" -" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -" struct Flags: u16 {\n" -" /// Clear to send.\n" -" const CTS = 1 << 0;\n" -" /// Data set ready.\n" -" const DSR = 1 << 1;\n" -" /// Data carrier detect.\n" -" const DCD = 1 << 2;\n" -" /// UART busy transmitting data.\n" -" const BUSY = 1 << 3;\n" -" /// Receive FIFO is empty.\n" -" const RXFE = 1 << 4;\n" -" /// Transmit FIFO is full.\n" -" const TXFF = 1 << 5;\n" -" /// Receive FIFO is full.\n" -" const RXFF = 1 << 6;\n" -" /// Transmit FIFO is empty.\n" -" const TXFE = 1 << 7;\n" -" /// Ring indicator.\n" -" const RI = 1 << 8;\n" -" }\n" -"}\n" -"// ANCHOR_END: Flags\n" -"\n" -"bitflags! {\n" -" /// Flags from the UART Receive Status Register / Error Clear Register.\n" -" #[repr(transparent)]\n" -" #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -" struct ReceiveStatus: u16 {\n" -" /// Framing error.\n" -" const FE = 1 << 0;\n" -" /// Parity error.\n" -" const PE = 1 << 1;\n" -" /// Break error.\n" -" const BE = 1 << 2;\n" -" /// Overrun error.\n" -" const OE = 1 << 3;\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Registers\n" -"#[repr(C, align(4))]\n" -"struct Registers {\n" -" dr: u16,\n" -" _reserved0: [u8; 2],\n" -" rsr: ReceiveStatus,\n" -" _reserved1: [u8; 19],\n" -" fr: Flags,\n" -" _reserved2: [u8; 6],\n" -" ilpr: u8,\n" -" _reserved3: [u8; 3],\n" -" ibrd: u16,\n" -" _reserved4: [u8; 2],\n" -" fbrd: u8,\n" -" _reserved5: [u8; 3],\n" -" lcr_h: u8,\n" -" _reserved6: [u8; 3],\n" -" cr: u16,\n" -" _reserved7: [u8; 3],\n" -" ifls: u8,\n" -" _reserved8: [u8; 3],\n" -" imsc: u16,\n" -" _reserved9: [u8; 2],\n" -" ris: u16,\n" -" _reserved10: [u8; 2],\n" -" mis: u16,\n" -" _reserved11: [u8; 2],\n" -" icr: u16,\n" -" _reserved12: [u8; 2],\n" -" dmacr: u8,\n" -" _reserved13: [u8; 3],\n" -"}\n" -"// ANCHOR_END: Registers\n" -"\n" -"// ANCHOR: Uart\n" -"/// Driver for a PL011 UART.\n" -"#[derive(Debug)]\n" -"pub struct Uart {\n" -" registers: *mut Registers,\n" -"}\n" -"\n" -"impl Uart {\n" -" /// Constructs a new instance of the UART driver for a PL011 device at " -"the\n" +"/// Constructs a new instance of the RTC driver for a PL031 device at the\n" " /// given base address.\n" " ///\n" " /// # Safety\n" " ///\n" " /// The given base address must point to the MMIO control registers of " "a\n" -" /// PL011 device, which must be mapped into the address space of the " +" /// PL031 device, which must be mapped into the address space of the " "process\n" " /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u32) -> Self {\n" -" Self {\n" -" registers: base_address as *mut Registers,\n" -" }\n" -" }\n" -"\n" -" /// Writes a single byte to the UART.\n" -" pub fn write_byte(&self, byte: u8) {\n" -" // Wait until there is room in the TX buffer.\n" -" while self.read_flag_register().contains(Flags::TXFF) {}\n" -"\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe {\n" -" // Write to the TX buffer.\n" -" addr_of_mut!((*self.registers).dr).write_volatile(byte.into());\n" -" }\n" -"\n" -" // Wait until the UART is no longer busy.\n" -" while self.read_flag_register().contains(Flags::BUSY) {}\n" -" }\n" -"\n" -" /// Reads and returns a pending byte, or `None` if nothing has been " -"received.\n" -" pub fn read_byte(&self) -> Option {\n" -" if self.read_flag_register().contains(Flags::RXFE) {\n" -" None\n" -" } else {\n" -" let data = unsafe { addr_of!((*self.registers).dr)." -"read_volatile() };\n" -" // TODO: Check for error conditions in bits 8-11.\n" -" Some(data as u8)\n" -" }\n" -" }\n" -"\n" -" fn read_flag_register(&self) -> Flags {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL011 device which is appropriately mapped.\n" -" unsafe { addr_of!((*self.registers).fr).read_volatile() }\n" -" }\n" -"}\n" -"// ANCHOR_END: Uart\n" -"\n" -"impl Write for Uart {\n" -" fn write_str(&mut self, s: &str) -> fmt::Result {\n" -" for c in s.as_bytes() {\n" -" self.write_byte(*c);\n" -" }\n" -" Ok(())\n" -" }\n" -"}\n" -"\n" -"// Safe because it just contains a pointer to device memory, which can be\n" -"// accessed from any context.\n" -"unsafe impl Send for Uart {}\n" -"```" msgstr "" +"/// Constructs a new instance of the RTC driver for a PL031 device at the\n" +" /// given base address.\n" +" ///\n" +" /// # Safety\n" +" ///\n" +" /// The given base address must point to the MMIO control registers of " +"a\n" +" /// PL031 device, which must be mapped into the address space of the " +"process\n" +" /// as device memory and not have any other aliases.\n" -#: src/exercises/bare-metal/rtc.md:389 +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Reads the current RTC value.\n" +msgstr "/// Reads the current RTC value.\n" + +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```toml\n" -"[workspace]\n" -"\n" -"[package]\n" -"name = \"rtc\"\n" -"version = \"0.1.0\"\n" -"edition = \"2021\"\n" -"publish = false\n" -"\n" -"[dependencies]\n" -"arm-gic = \"0.1.0\"\n" -"bitflags = \"2.0.0\"\n" -"chrono = { version = \"0.4.24\", default-features = false }\n" -"log = \"0.4.17\"\n" -"smccc = \"0.1.1\"\n" -"spin = \"0.9.8\"\n" -"\n" -"[build-dependencies]\n" -"cc = \"1.0.73\"\n" -"```" +"// Safe because we know that self.registers points to the control\n" +" // registers of a PL031 device which is appropriately mapped.\n" msgstr "" +"// Safe because we know that self.registers points to the control\n" +" // registers of a PL031 device which is appropriately mapped.\n" -#: src/exercises/bare-metal/rtc.md:410 -msgid "`build.rs` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:414 +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"use cc::Build;\n" -"use std::env;\n" -"\n" -"fn main() {\n" -" #[cfg(target_os = \"linux\")]\n" -" env::set_var(\"CROSS_COMPILE\", \"aarch64-linux-gnu\");\n" -" #[cfg(not(target_os = \"linux\"))]\n" -" env::set_var(\"CROSS_COMPILE\", \"aarch64-none-elf\");\n" -"\n" -" Build::new()\n" -" .file(\"entry.S\")\n" -" .file(\"exceptions.S\")\n" -" .file(\"idmap.S\")\n" -" .compile(\"empty\")\n" -"}\n" -"```" +"/// Writes a match value. When the RTC value matches this then an interrupt\n" +" /// will be generated (if it is enabled).\n" msgstr "" +"/// Writes a match value. When the RTC value matches this then an interrupt\n" +" /// will be generated (if it is enabled).\n" -#: src/exercises/bare-metal/rtc.md:446 -msgid "`entry.S` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:450 +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```armasm\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -".macro adr_l, reg:req, sym:req\n" -"\tadrp \\reg, \\sym\n" -"\tadd \\reg, \\reg, :lo12:\\sym\n" -".endm\n" -"\n" -".macro mov_i, reg:req, imm:req\n" -"\tmovz \\reg, :abs_g3:\\imm\n" -"\tmovk \\reg, :abs_g2_nc:\\imm\n" -"\tmovk \\reg, :abs_g1_nc:\\imm\n" -"\tmovk \\reg, :abs_g0_nc:\\imm\n" -".endm\n" -"\n" -".set .L_MAIR_DEV_nGnRE,\t0x04\n" -".set .L_MAIR_MEM_WBWA,\t0xff\n" -".set .Lmairval, .L_MAIR_DEV_nGnRE | (.L_MAIR_MEM_WBWA << 8)\n" -"\n" -"/* 4 KiB granule size for TTBR0_EL1. */\n" -".set .L_TCR_TG0_4KB, 0x0 << 14\n" -"/* 4 KiB granule size for TTBR1_EL1. */\n" -".set .L_TCR_TG1_4KB, 0x2 << 30\n" -"/* Disable translation table walk for TTBR1_EL1, generating a translation " -"fault instead. */\n" -".set .L_TCR_EPD1, 0x1 << 23\n" -"/* Translation table walks for TTBR0_EL1 are inner sharable. */\n" -".set .L_TCR_SH_INNER, 0x3 << 12\n" -"/*\n" -" * Translation table walks for TTBR0_EL1 are outer write-back read-allocate " -"write-allocate\n" -" * cacheable.\n" -" */\n" -".set .L_TCR_RGN_OWB, 0x1 << 10\n" -"/*\n" -" * Translation table walks for TTBR0_EL1 are inner write-back read-allocate " -"write-allocate\n" -" * cacheable.\n" -" */\n" -".set .L_TCR_RGN_IWB, 0x1 << 8\n" -"/* Size offset for TTBR0_EL1 is 2**39 bytes (512 GiB). */\n" -".set .L_TCR_T0SZ_512, 64 - 39\n" -".set .Ltcrval, .L_TCR_TG0_4KB | .L_TCR_TG1_4KB | .L_TCR_EPD1 | ." -"L_TCR_RGN_OWB\n" -".set .Ltcrval, .Ltcrval | .L_TCR_RGN_IWB | .L_TCR_SH_INNER | ." -"L_TCR_T0SZ_512\n" -"\n" -"/* Stage 1 instruction access cacheability is unaffected. */\n" -".set .L_SCTLR_ELx_I, 0x1 << 12\n" -"/* SP alignment fault if SP is not aligned to a 16 byte boundary. */\n" -".set .L_SCTLR_ELx_SA, 0x1 << 3\n" -"/* Stage 1 data access cacheability is unaffected. */\n" -".set .L_SCTLR_ELx_C, 0x1 << 2\n" -"/* EL0 and EL1 stage 1 MMU enabled. */\n" -".set .L_SCTLR_ELx_M, 0x1 << 0\n" -"/* Privileged Access Never is unchanged on taking an exception to EL1. */\n" -".set .L_SCTLR_EL1_SPAN, 0x1 << 23\n" -"/* SETEND instruction disabled at EL0 in aarch32 mode. */\n" -".set .L_SCTLR_EL1_SED, 0x1 << 8\n" -"/* Various IT instructions are disabled at EL0 in aarch32 mode. */\n" -".set .L_SCTLR_EL1_ITD, 0x1 << 7\n" -".set .L_SCTLR_EL1_RES1, (0x1 << 11) | (0x1 << 20) | (0x1 << 22) | (0x1 << " -"28) | (0x1 << 29)\n" -".set .Lsctlrval, .L_SCTLR_ELx_M | .L_SCTLR_ELx_C | .L_SCTLR_ELx_SA | ." -"L_SCTLR_EL1_ITD | .L_SCTLR_EL1_SED\n" -".set .Lsctlrval, .Lsctlrval | .L_SCTLR_ELx_I | .L_SCTLR_EL1_SPAN | ." -"L_SCTLR_EL1_RES1\n" -"\n" -"/**\n" -" * This is a generic entry point for an image. It carries out the operations " -"required to prepare the\n" -" * loaded image to be run. Specifically, it zeroes the bss section using " -"registers x25 and above,\n" -" * prepares the stack, enables floating point, and sets up the exception " -"vector. It preserves x0-x3\n" -" * for the Rust entry point, as these may contain boot parameters.\n" -" */\n" -".section .init.entry, \"ax\"\n" -".global entry\n" -"entry:\n" -"\t/* Load and apply the memory management configuration, ready to enable MMU " -"and caches. */\n" -"\tadrp x30, idmap\n" -"\tmsr ttbr0_el1, x30\n" -"\n" -"\tmov_i x30, .Lmairval\n" -"\tmsr mair_el1, x30\n" -"\n" -"\tmov_i x30, .Ltcrval\n" -"\t/* Copy the supported PA range into TCR_EL1.IPS. */\n" -"\tmrs x29, id_aa64mmfr0_el1\n" -"\tbfi x30, x29, #32, #4\n" -"\n" -"\tmsr tcr_el1, x30\n" -"\n" -"\tmov_i x30, .Lsctlrval\n" -"\n" -"\t/*\n" -"\t * Ensure everything before this point has completed, then invalidate any " -"potentially stale\n" -"\t * local TLB entries before they start being used.\n" -"\t */\n" -"\tisb\n" -"\ttlbi vmalle1\n" -"\tic iallu\n" -"\tdsb nsh\n" -"\tisb\n" -"\n" -"\t/*\n" -"\t * Configure sctlr_el1 to enable MMU and cache and don't proceed until " -"this has completed.\n" -"\t */\n" -"\tmsr sctlr_el1, x30\n" -"\tisb\n" -"\n" -"\t/* Disable trapping floating point access in EL1. */\n" -"\tmrs x30, cpacr_el1\n" -"\torr x30, x30, #(0x3 << 20)\n" -"\tmsr cpacr_el1, x30\n" -"\tisb\n" -"\n" -"\t/* Zero out the bss section. */\n" -"\tadr_l x29, bss_begin\n" -"\tadr_l x30, bss_end\n" -"0:\tcmp x29, x30\n" -"\tb.hs 1f\n" -"\tstp xzr, xzr, [x29], #16\n" -"\tb 0b\n" -"\n" -"1:\t/* Prepare the stack. */\n" -"\tadr_l x30, boot_stack_end\n" -"\tmov sp, x30\n" -"\n" -"\t/* Set up exception vector. */\n" -"\tadr x30, vector_table_el1\n" -"\tmsr vbar_el1, x30\n" -"\n" -"\t/* Call into Rust code. */\n" -"\tbl main\n" -"\n" -"\t/* Loop forever waiting for interrupts. */\n" -"2:\twfi\n" -"\tb 2b\n" -"```" +"/// Returns whether the match register matches the RTC value, whether or " +"not\n" +" /// the interrupt is enabled.\n" msgstr "" +"/// Returns whether the match register matches the RTC value, whether or " +"not\n" +" /// the interrupt is enabled.\n" -#: src/exercises/bare-metal/rtc.md:595 -msgid "`exceptions.S` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:599 +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```armasm\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -"/**\n" -" * Saves the volatile registers onto the stack. This currently takes 14\n" -" * instructions, so it can be used in exception handlers with 18 " -"instructions\n" -" * left.\n" -" *\n" -" * On return, x0 and x1 are initialised to elr_el2 and spsr_el2 " -"respectively,\n" -" * which can be used as the first and second arguments of a subsequent " -"call.\n" -" */\n" -".macro save_volatile_to_stack\n" -"\t/* Reserve stack space and save registers x0-x18, x29 & x30. */\n" -"\tstp x0, x1, [sp, #-(8 * 24)]!\n" -"\tstp x2, x3, [sp, #8 * 2]\n" -"\tstp x4, x5, [sp, #8 * 4]\n" -"\tstp x6, x7, [sp, #8 * 6]\n" -"\tstp x8, x9, [sp, #8 * 8]\n" -"\tstp x10, x11, [sp, #8 * 10]\n" -"\tstp x12, x13, [sp, #8 * 12]\n" -"\tstp x14, x15, [sp, #8 * 14]\n" -"\tstp x16, x17, [sp, #8 * 16]\n" -"\tstr x18, [sp, #8 * 18]\n" -"\tstp x29, x30, [sp, #8 * 20]\n" -"\n" -"\t/*\n" -"\t * Save elr_el1 & spsr_el1. This such that we can take nested exception\n" -"\t * and still be able to unwind.\n" -"\t */\n" -"\tmrs x0, elr_el1\n" -"\tmrs x1, spsr_el1\n" -"\tstp x0, x1, [sp, #8 * 22]\n" -".endm\n" -"\n" -"/**\n" -" * Restores the volatile registers from the stack. This currently takes 14\n" -" * instructions, so it can be used in exception handlers while still leaving " -"18\n" -" * instructions left; if paired with save_volatile_to_stack, there are 4\n" -" * instructions to spare.\n" -" */\n" -".macro restore_volatile_from_stack\n" -"\t/* Restore registers x2-x18, x29 & x30. */\n" -"\tldp x2, x3, [sp, #8 * 2]\n" -"\tldp x4, x5, [sp, #8 * 4]\n" -"\tldp x6, x7, [sp, #8 * 6]\n" -"\tldp x8, x9, [sp, #8 * 8]\n" -"\tldp x10, x11, [sp, #8 * 10]\n" -"\tldp x12, x13, [sp, #8 * 12]\n" -"\tldp x14, x15, [sp, #8 * 14]\n" -"\tldp x16, x17, [sp, #8 * 16]\n" -"\tldr x18, [sp, #8 * 18]\n" -"\tldp x29, x30, [sp, #8 * 20]\n" -"\n" -"\t/* Restore registers elr_el1 & spsr_el1, using x0 & x1 as scratch. */\n" -"\tldp x0, x1, [sp, #8 * 22]\n" -"\tmsr elr_el1, x0\n" -"\tmsr spsr_el1, x1\n" -"\n" -"\t/* Restore x0 & x1, and release stack space. */\n" -"\tldp x0, x1, [sp], #8 * 24\n" -".endm\n" -"\n" -"/**\n" -" * This is a generic handler for exceptions taken at the current EL while " -"using\n" -" * SP0. It behaves similarly to the SPx case by first switching to SPx, " -"doing\n" -" * the work, then switching back to SP0 before returning.\n" -" *\n" -" * Switching to SPx and calling the Rust handler takes 16 instructions. To\n" -" * restore and return we need an additional 16 instructions, so we can " -"implement\n" -" * the whole handler within the allotted 32 instructions.\n" -" */\n" -".macro current_exception_sp0 handler:req\n" -"\tmsr spsel, #1\n" -"\tsave_volatile_to_stack\n" -"\tbl \\handler\n" -"\trestore_volatile_from_stack\n" -"\tmsr spsel, #0\n" -"\teret\n" -".endm\n" -"\n" -"/**\n" -" * This is a generic handler for exceptions taken at the current EL while " -"using\n" -" * SPx. It saves volatile registers, calls the Rust handler, restores " -"volatile\n" -" * registers, then returns.\n" -" *\n" -" * This also works for exceptions taken from EL0, if we don't care about\n" -" * non-volatile registers.\n" -" *\n" -" * Saving state and jumping to the Rust handler takes 15 instructions, and\n" -" * restoring and returning also takes 15 instructions, so we can fit the " -"whole\n" -" * handler in 30 instructions, under the limit of 32.\n" -" */\n" -".macro current_exception_spx handler:req\n" -"\tsave_volatile_to_stack\n" -"\tbl \\handler\n" -"\trestore_volatile_from_stack\n" -"\teret\n" -".endm\n" -"\n" -".section .text.vector_table_el1, \"ax\"\n" -".global vector_table_el1\n" -".balign 0x800\n" -"vector_table_el1:\n" -"sync_cur_sp0:\n" -"\tcurrent_exception_sp0 sync_exception_current\n" -"\n" -".balign 0x80\n" -"irq_cur_sp0:\n" -"\tcurrent_exception_sp0 irq_current\n" -"\n" -".balign 0x80\n" -"fiq_cur_sp0:\n" -"\tcurrent_exception_sp0 fiq_current\n" -"\n" -".balign 0x80\n" -"serr_cur_sp0:\n" -"\tcurrent_exception_sp0 serr_current\n" -"\n" -".balign 0x80\n" -"sync_cur_spx:\n" -"\tcurrent_exception_spx sync_exception_current\n" -"\n" -".balign 0x80\n" -"irq_cur_spx:\n" -"\tcurrent_exception_spx irq_current\n" -"\n" -".balign 0x80\n" -"fiq_cur_spx:\n" -"\tcurrent_exception_spx fiq_current\n" -"\n" -".balign 0x80\n" -"serr_cur_spx:\n" -"\tcurrent_exception_spx serr_current\n" -"\n" -".balign 0x80\n" -"sync_lower_64:\n" -"\tcurrent_exception_spx sync_lower\n" -"\n" -".balign 0x80\n" -"irq_lower_64:\n" -"\tcurrent_exception_spx irq_lower\n" -"\n" -".balign 0x80\n" -"fiq_lower_64:\n" -"\tcurrent_exception_spx fiq_lower\n" -"\n" -".balign 0x80\n" -"serr_lower_64:\n" -"\tcurrent_exception_spx serr_lower\n" -"\n" -".balign 0x80\n" -"sync_lower_32:\n" -"\tcurrent_exception_spx sync_lower\n" -"\n" -".balign 0x80\n" -"irq_lower_32:\n" -"\tcurrent_exception_spx irq_lower\n" -"\n" -".balign 0x80\n" -"fiq_lower_32:\n" -"\tcurrent_exception_spx fiq_lower\n" -"\n" -".balign 0x80\n" -"serr_lower_32:\n" -"\tcurrent_exception_spx serr_lower\n" -"```" +"/// Returns whether there is currently an interrupt pending.\n" +" ///\n" +" /// This should be true if and only if `matched` returns true and the\n" +" /// interrupt is masked.\n" msgstr "" +"/// Returns whether there is currently an interrupt pending.\n" +" ///\n" +" /// This should be true if and only if `matched` returns true and the\n" +" /// interrupt is masked.\n" -#: src/exercises/bare-metal/rtc.md:780 -msgid "`idmap.S` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:784 +#: src/exercises/bare-metal/solutions-afternoon.md msgid "" -"```armasm\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -".set .L_TT_TYPE_BLOCK, 0x1\n" -".set .L_TT_TYPE_PAGE, 0x3\n" -".set .L_TT_TYPE_TABLE, 0x3\n" -"\n" -"/* Access flag. */\n" -".set .L_TT_AF, 0x1 << 10\n" -"/* Not global. */\n" -".set .L_TT_NG, 0x1 << 11\n" -".set .L_TT_XN, 0x3 << 53\n" -"\n" -".set .L_TT_MT_DEV, 0x0 << 2\t\t\t// MAIR #0 (DEV_nGnRE)\n" -".set .L_TT_MT_MEM, (0x1 << 2) | (0x3 << 8)\t// MAIR #1 (MEM_WBWA), inner " -"shareable\n" -"\n" -".set .L_BLOCK_DEV, .L_TT_TYPE_BLOCK | .L_TT_MT_DEV | .L_TT_AF | .L_TT_XN\n" -".set .L_BLOCK_MEM, .L_TT_TYPE_BLOCK | .L_TT_MT_MEM | .L_TT_AF | .L_TT_NG\n" -"\n" -".section \".rodata.idmap\", \"a\", %progbits\n" -".global idmap\n" -".align 12\n" -"idmap:\n" -"\t/* level 1 */\n" -"\t.quad\t\t.L_BLOCK_DEV | 0x0\t\t // 1 GiB of device mappings\n" -"\t.quad\t\t.L_BLOCK_MEM | 0x40000000\t// 1 GiB of DRAM\n" -"\t.fill\t\t254, 8, 0x0\t\t\t// 254 GiB of unmapped VA space\n" -"\t.quad\t\t.L_BLOCK_DEV | 0x4000000000 // 1 GiB of device mappings\n" -"\t.fill\t\t255, 8, 0x0\t\t\t// 255 GiB of remaining VA space\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:829 -msgid "`image.ld` (you shouldn't need to change this):" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:833 -msgid "" -"```ld\n" -"/*\n" -" * Copyright 2023 Google LLC\n" -" *\n" -" * Licensed under the Apache License, Version 2.0 (the \"License\");\n" -" * you may not use this file except in compliance with the License.\n" -" * You may obtain a copy of the License at\n" -" *\n" -" * https://www.apache.org/licenses/LICENSE-2.0\n" -" *\n" -" * Unless required by applicable law or agreed to in writing, software\n" -" * distributed under the License is distributed on an \"AS IS\" BASIS,\n" -" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -" * See the License for the specific language governing permissions and\n" -" * limitations under the License.\n" -" */\n" -"\n" -"/*\n" -" * Code will start running at this symbol which is placed at the start of " +"/// Sets or clears the interrupt mask.\n" +" ///\n" +" /// When the mask is true the interrupt is enabled; when it is false " "the\n" -" * image.\n" -" */\n" -"ENTRY(entry)\n" -"\n" -"MEMORY\n" -"{\n" -"\timage : ORIGIN = 0x40080000, LENGTH = 2M\n" -"}\n" -"\n" -"SECTIONS\n" -"{\n" -"\t/*\n" -"\t * Collect together the code.\n" -"\t */\n" -"\t.init : ALIGN(4096) {\n" -"\t\ttext_begin = .;\n" -"\t\t*(.init.entry)\n" -"\t\t*(.init.*)\n" -"\t} >image\n" -"\t.text : {\n" -"\t\t*(.text.*)\n" -"\t} >image\n" -"\ttext_end = .;\n" -"\n" -"\t/*\n" -"\t * Collect together read-only data.\n" -"\t */\n" -"\t.rodata : ALIGN(4096) {\n" -"\t\trodata_begin = .;\n" -"\t\t*(.rodata.*)\n" -"\t} >image\n" -"\t.got : {\n" -"\t\t*(.got)\n" -"\t} >image\n" -"\trodata_end = .;\n" -"\n" -"\t/*\n" -"\t * Collect together the read-write data including .bss at the end which\n" -"\t * will be zero'd by the entry code.\n" -"\t */\n" -"\t.data : ALIGN(4096) {\n" -"\t\tdata_begin = .;\n" -"\t\t*(.data.*)\n" -"\t\t/*\n" -"\t\t * The entry point code assumes that .data is a multiple of 32\n" -"\t\t * bytes long.\n" -"\t\t */\n" -"\t\t. = ALIGN(32);\n" -"\t\tdata_end = .;\n" -"\t} >image\n" -"\n" -"\t/* Everything beyond this point will not be included in the binary. */\n" -"\tbin_end = .;\n" -"\n" -"\t/* The entry point code assumes that .bss is 16-byte aligned. */\n" -"\t.bss : ALIGN(16) {\n" -"\t\tbss_begin = .;\n" -"\t\t*(.bss.*)\n" -"\t\t*(COMMON)\n" -"\t\t. = ALIGN(16);\n" -"\t\tbss_end = .;\n" -"\t} >image\n" -"\n" -"\t.stack (NOLOAD) : ALIGN(4096) {\n" -"\t\tboot_stack_begin = .;\n" -"\t\t. += 40 * 4096;\n" -"\t\t. = ALIGN(4096);\n" -"\t\tboot_stack_end = .;\n" -"\t} >image\n" -"\n" -"\t. = ALIGN(4K);\n" -"\tPROVIDE(dma_region = .);\n" -"\n" -"\t/*\n" -"\t * Remove unused sections from the image.\n" -"\t */\n" -"\t/DISCARD/ : {\n" -"\t\t/* The image loads itself so doesn't need these sections. */\n" -"\t\t*(.gnu.hash)\n" -"\t\t*(.hash)\n" -"\t\t*(.interp)\n" -"\t\t*(.eh_frame_hdr)\n" -"\t\t*(.eh_frame)\n" -"\t\t*(.note.gnu.build-id)\n" -"\t}\n" -"}\n" -"```" +" /// interrupt is disabled.\n" msgstr "" +"/// Sets or clears the interrupt mask.\n" +" ///\n" +" /// When the mask is true the interrupt is enabled; when it is false " +"the\n" +" /// interrupt is disabled.\n" -#: src/exercises/bare-metal/rtc.md:940 -msgid "`Makefile` (you shouldn't need to change this):" -msgstr "" +#: src/exercises/bare-metal/solutions-afternoon.md +msgid "/// Clears a pending interrupt, if any.\n" +msgstr "/// Clears a pending interrupt, if any.\n" -#: src/exercises/bare-metal/rtc.md:944 -msgid "" -"```makefile\n" -"# Copyright 2023 Google LLC\n" -"#\n" -"# Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"# you may not use this file except in compliance with the License.\n" -"# You may obtain a copy of the License at\n" -"#\n" -"# http://www.apache.org/licenses/LICENSE-2.0\n" -"#\n" -"# Unless required by applicable law or agreed to in writing, software\n" -"# distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"# See the License for the specific language governing permissions and\n" -"# limitations under the License.\n" -"\n" -"UNAME := $(shell uname -s)\n" -"ifeq ($(UNAME),Linux)\n" -"\tTARGET = aarch64-linux-gnu\n" -"else\n" -"\tTARGET = aarch64-none-elf\n" -"endif\n" -"OBJCOPY = $(TARGET)-objcopy\n" -"\n" -".PHONY: build qemu_minimal qemu qemu_logger\n" -"\n" -"all: rtc.bin\n" -"\n" -"build:\n" -"\tcargo build\n" -"\n" -"rtc.bin: build\n" -"\t$(OBJCOPY) -O binary target/aarch64-unknown-none/debug/rtc $@\n" -"\n" -"qemu: rtc.bin\n" -"\tqemu-system-aarch64 -machine virt,gic-version=3 -cpu max -serial mon:stdio " -"-display none -kernel $< -s\n" -"\n" -"clean:\n" -"\tcargo clean\n" -"\trm -f *.bin\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:989 -msgid "" -"```toml\n" -"[build]\n" -"target = \"aarch64-unknown-none\"\n" -"rustflags = [\"-C\", \"link-arg=-Timage.ld\"]\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/rtc.md:995 -msgid "Run the code in QEMU with `make qemu`." -msgstr "" - -#: src/concurrency.md:1 +#: src/concurrency.md msgid "Welcome to Concurrency in Rust" msgstr "歡迎使用 Rust 的並行程式設計" -#: src/concurrency.md:3 +#: src/concurrency.md msgid "" "Rust has full support for concurrency using OS threads with mutexes and " "channels." msgstr "Rust 使用 OS 執行緒搭配著互斥鎖和通道來完整支援並行處理。" -#: src/concurrency.md:6 +#: src/concurrency.md msgid "" "The Rust type system plays an important role in making many concurrency bugs " "compile time bugs. This is often referred to as _fearless concurrency_ since " @@ -16970,121 +19300,193 @@ msgstr "" "在將許多執行期並行錯誤轉換為編譯期錯誤的過程中,Rust 型別系統扮演了 重要角" "色。這通常稱為「無懼並行」,因為你可以依賴編譯器, 確保執行期能夠正確運作。" -#: src/concurrency/threads.md:3 +#: src/concurrency.md +msgid "" +"Rust lets us access OS concurrency toolkit: threads, sync. primitives, etc." +msgstr "" + +#: src/concurrency.md +msgid "" +"The type system gives us safety for concurrency without any special features." +msgstr "" + +#: src/concurrency.md +msgid "" +"The same tools that help with \"concurrent\" access in a single thread (e." +"g., a called function that might mutate an argument or save references to it " +"to read later) save us from multi-threading issues." +msgstr "" + +#: src/concurrency/threads.md msgid "Rust threads work similarly to threads in other languages:" msgstr "Rust 執行緒的運作方式與其他語言類似:" -#: src/concurrency/threads.md:5 -msgid "" -"```rust,editable\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" thread::spawn(|| {\n" -" for i in 1..10 {\n" -" println!(\"Count in thread: {i}!\");\n" -" thread::sleep(Duration::from_millis(5));\n" -" }\n" -" });\n" -"\n" -" for i in 1..5 {\n" -" println!(\"Main thread: {i}\");\n" -" thread::sleep(Duration::from_millis(5));\n" -" }\n" -"}\n" -"```" +#: src/concurrency/threads.md +msgid "\"Count in thread: {i}!\"" msgstr "" -"```rust,editable\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" thread::spawn(|| {\n" -" for i in 1..10 {\n" -" println!(\"Count in thread: {i}!\");\n" -" thread::sleep(Duration::from_millis(5));\n" -" }\n" -" });\n" -"\n" -" for i in 1..5 {\n" -" println!(\"Main thread: {i}\");\n" -" thread::sleep(Duration::from_millis(5));\n" -" }\n" -"}\n" -"```" -#: src/concurrency/threads.md:24 +#: src/concurrency/threads.md +msgid "\"Main thread: {i}\"" +msgstr "" + +#: src/concurrency/threads.md msgid "Threads are all daemon threads, the main thread does not wait for them." msgstr "執行緒都是 daemon 執行緒,主執行緒不會等待這類執行緒完成運作。" -#: src/concurrency/threads.md:25 +#: src/concurrency/threads.md msgid "Thread panics are independent of each other." msgstr "執行緒恐慌均為各自獨立,並非彼此相關。" -#: src/concurrency/threads.md:26 +#: src/concurrency/threads.md msgid "Panics can carry a payload, which can be unpacked with `downcast_ref`." msgstr "如果恐慌附帶酬載,可使用 `downcast_ref` 解除封裝。" -#: src/concurrency/threads.md:32 -msgid "" -"Notice that the thread is stopped before it reaches 10 — the main thread is " -"not waiting." +#: src/concurrency/threads.md +msgid "Rust thread APIs look not too different from e.g. C++ ones." msgstr "" -"請注意,執行緒會在達到 10 之前停止運作,因為主執行緒不會 等待其完成運作。" -#: src/concurrency/threads.md:35 +#: src/concurrency/threads.md +#, fuzzy +msgid "Run the example." +msgstr "Rust by Example" + +#: src/concurrency/threads.md +msgid "" +"5ms timing is loose enough that main and spawned threads stay mostly in " +"lockstep." +msgstr "" + +#: src/concurrency/threads.md +msgid "Notice that the program ends before the spawned thread reaches 10!" +msgstr "" + +#: src/concurrency/threads.md +msgid "" +"This is because main ends the program and spawned threads do not make it " +"persist." +msgstr "" + +#: src/concurrency/threads.md +msgid "Compare to pthreads/C++ std::thread/boost::thread if desired." +msgstr "" + +#: src/concurrency/threads.md +msgid "How do we wait around for the spawned thread to complete?" +msgstr "" + +#: src/concurrency/threads.md +#, fuzzy +msgid "" +"[`thread::spawn`](https://doc.rust-lang.org/std/thread/fn.spawn.html) " +"returns a `JoinHandle`. Look at the docs." +msgstr "" +"[`Drop`](https://doc.rust-lang.org/std/ops/trait.Drop.html) 用於定義解構函" +"式。" + +#: src/concurrency/threads.md +msgid "" +"`JoinHandle` has a [`.join()`](https://doc.rust-lang.org/std/thread/struct." +"JoinHandle.html#method.join) method that blocks." +msgstr "" + +#: src/concurrency/threads.md +#, fuzzy msgid "" "Use `let handle = thread::spawn(...)` and later `handle.join()` to wait for " -"the thread to finish." +"the thread to finish and have the program count all the way to 10." msgstr "" "請依序使用 `let handle = thread::spawn(...)` 和 `handle.join()`,等待 執行緒" "完成運作。" -#: src/concurrency/threads.md:38 -msgid "Trigger a panic in the thread, notice how this doesn't affect `main`." -msgstr "在執行緒中觸發恐慌,請注意,這不會影響 `main`。" +#: src/concurrency/threads.md +msgid "Now what if we want to return a value?" +msgstr "" -#: src/concurrency/threads.md:40 +#: src/concurrency/threads.md +msgid "Look at docs again:" +msgstr "" + +#: src/concurrency/threads.md +#, fuzzy +msgid "" +"[`thread::spawn`](https://doc.rust-lang.org/std/thread/fn.spawn.html)'s " +"closure returns `T`" +msgstr "" +"但是,你可以使用[限定範圍執行緒](https://doc.rust-lang.org/std/thread/fn." +"scope.html)執行這項功能:" + +#: src/concurrency/threads.md +msgid "" +"`JoinHandle` [`.join()`](https://doc.rust-lang.org/std/thread/struct." +"JoinHandle.html#method.join) returns `thread::Result`" +msgstr "" + +#: src/concurrency/threads.md +#, fuzzy msgid "" "Use the `Result` return value from `handle.join()` to get access to the " -"panic payload. This is a good time to talk about [`Any`](https://doc.rust-" -"lang.org/std/any/index.html)." +"returned value." msgstr "" "使用 `handle.join()` 的 `Result` 傳回值,取得恐慌酬載的 存取權。這個階段是提" "起 [`Any`](https://doc.rust-lang.org/std/any/index.html) 的好時機。" -#: src/concurrency/scoped-threads.md:3 +#: src/concurrency/threads.md +msgid "Ok, what about the other case?" +msgstr "" + +#: src/concurrency/threads.md +#, fuzzy +msgid "Trigger a panic in the thread. Note that this doesn't panic `main`." +msgstr "在執行緒中觸發恐慌,請注意,這不會影響 `main`。" + +#: src/concurrency/threads.md +#, fuzzy +msgid "" +"Access the panic payload. This is a good time to talk about [`Any`](https://" +"doc.rust-lang.org/std/any/index.html)." +msgstr "" +"使用 `handle.join()` 的 `Result` 傳回值,取得恐慌酬載的 存取權。這個階段是提" +"起 [`Any`](https://doc.rust-lang.org/std/any/index.html) 的好時機。" + +#: src/concurrency/threads.md +msgid "Now we can return values from threads! What about taking inputs?" +msgstr "" + +#: src/concurrency/threads.md +msgid "Capture something by reference in the thread closure." +msgstr "" + +#: src/concurrency/threads.md +msgid "An error message indicates we must move it." +msgstr "" + +#: src/concurrency/threads.md +msgid "Move it in, see we can compute and then return a derived value." +msgstr "" + +#: src/concurrency/threads.md +msgid "If we want to borrow?" +msgstr "" + +#: src/concurrency/threads.md +msgid "" +"Main kills child threads when it returns, but another function would just " +"return and leave them running." +msgstr "" + +#: src/concurrency/threads.md +msgid "That would be stack use-after-return, which violates memory safety!" +msgstr "" + +#: src/concurrency/threads.md +msgid "How do we avoid this? see next slide." +msgstr "" + +#: src/concurrency/scoped-threads.md msgid "Normal threads cannot borrow from their environment:" msgstr "一般執行緒無法借用環境的資源:" -#: src/concurrency/scoped-threads.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let s = String::from(\"Hello\");\n" -"\n" -" thread::spawn(|| {\n" -" println!(\"Length: {}\", s.len());\n" -" });\n" -"}\n" -"```" -msgstr "" -"```rust,editable,compile_fail\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let s = String::from(\"Hello\");\n" -"\n" -" thread::spawn(|| {\n" -" println!(\"Length: {}\", s.len());\n" -" });\n" -"}\n" -"```" - -#: src/concurrency/scoped-threads.md:17 +#: src/concurrency/scoped-threads.md msgid "" "However, you can use a [scoped thread](https://doc.rust-lang.org/std/thread/" "fn.scope.html) for this:" @@ -17092,37 +19494,7 @@ msgstr "" "但是,你可以使用[限定範圍執行緒](https://doc.rust-lang.org/std/thread/fn." "scope.html)執行這項功能:" -#: src/concurrency/scoped-threads.md:19 -msgid "" -"```rust,editable\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let s = String::from(\"Hello\");\n" -"\n" -" thread::scope(|scope| {\n" -" scope.spawn(|| {\n" -" println!(\"Length: {}\", s.len());\n" -" });\n" -" });\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let s = String::from(\"Hello\");\n" -"\n" -" thread::scope(|scope| {\n" -" scope.spawn(|| {\n" -" println!(\"Length: {}\", s.len());\n" -" });\n" -" });\n" -"}\n" -"```" - -#: src/concurrency/scoped-threads.md:37 +#: src/concurrency/scoped-threads.md msgid "" "The reason for that is that when the `thread::scope` function completes, all " "the threads are guaranteed to be joined, so they can return borrowed data." @@ -17130,7 +19502,7 @@ msgstr "" "原因在於 `thread::scope` 函式完成時,能保證所有執行緒都已加入,因此能夠傳回借" "用的資料。" -#: src/concurrency/scoped-threads.md:38 +#: src/concurrency/scoped-threads.md msgid "" "Normal Rust borrowing rules apply: you can either borrow mutably by one " "thread, or immutably by any number of threads." @@ -17138,7 +19510,7 @@ msgstr "" "適用 Rust 一般借用規則:可以由一個執行緒以可變方式借用,或者由任意數量的執行" "緒以不可變方式借用。" -#: src/concurrency/channels.md:3 +#: src/concurrency/channels.md msgid "" "Rust channels have two parts: a `Sender` and a `Receiver`. The two " "parts are connected via the channel, but you only see the end-points." @@ -17146,47 +19518,11 @@ msgstr "" "Rust 通道分為兩個部分:`Sender` 和 `Receiver`。這兩個部分 透過通道相" "連,但你只能看到端點。" -#: src/concurrency/channels.md:6 -msgid "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::channel();\n" -"\n" -" tx.send(10).unwrap();\n" -" tx.send(20).unwrap();\n" -"\n" -" println!(\"Received: {:?}\", rx.recv());\n" -" println!(\"Received: {:?}\", rx.recv());\n" -"\n" -" let tx2 = tx.clone();\n" -" tx2.send(30).unwrap();\n" -" println!(\"Received: {:?}\", rx.recv());\n" -"}\n" -"```" +#: src/concurrency/channels.md +msgid "\"Received: {:?}\"" msgstr "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::channel();\n" -"\n" -" tx.send(10).unwrap();\n" -" tx.send(20).unwrap();\n" -"\n" -" println!(\"Received: {:?}\", rx.recv());\n" -" println!(\"Received: {:?}\", rx.recv());\n" -"\n" -" let tx2 = tx.clone();\n" -" tx2.send(30).unwrap();\n" -" println!(\"Received: {:?}\", rx.recv());\n" -"}\n" -"```" -#: src/concurrency/channels.md:27 +#: src/concurrency/channels.md msgid "" "`mpsc` stands for Multi-Producer, Single-Consumer. `Sender` and `SyncSender` " "implement `Clone` (so you can make multiple producers) but `Receiver` does " @@ -17195,7 +19531,7 @@ msgstr "" "`mpsc` 代表多重生產者、唯一消費者。`Sender` 和 `SyncSender` 會實作 `Clone` " "(用於製作多重生產者),但 `Receiver` 不會。" -#: src/concurrency/channels.md:29 +#: src/concurrency/channels.md msgid "" "`send()` and `recv()` return `Result`. If they return `Err`, it means the " "counterpart `Sender` or `Receiver` is dropped and the channel is closed." @@ -17203,125 +19539,59 @@ msgstr "" "`send()` 和 `recv()` 會傳回 `Result`。如果傳回的是 `Err`,表示對應的 " "`Sender` 或 `Receiver` 已釋放,且通道已關閉。" -#: src/concurrency/channels/unbounded.md:3 +#: src/concurrency/channels/unbounded.md msgid "You get an unbounded and asynchronous channel with `mpsc::channel()`:" msgstr "你可以使用 `mpsc::channel()` 取得無界限的非同步通道:" -#: src/concurrency/channels/unbounded.md:5 -msgid "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::channel();\n" -"\n" -" thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" for i in 1..10 {\n" -" tx.send(format!(\"Message {i}\")).unwrap();\n" -" println!(\"{thread_id:?}: sent Message {i}\");\n" -" }\n" -" println!(\"{thread_id:?}: done\");\n" -" });\n" -" thread::sleep(Duration::from_millis(100));\n" -"\n" -" for msg in rx.iter() {\n" -" println!(\"Main: got {msg}\");\n" -" }\n" -"}\n" -"```" +#: src/concurrency/channels/unbounded.md src/concurrency/channels/bounded.md +msgid "\"Message {i}\"" msgstr "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::channel();\n" -"\n" -" thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" for i in 1..10 {\n" -" tx.send(format!(\"Message {i}\")).unwrap();\n" -" println!(\"{thread_id:?}: sent Message {i}\");\n" -" }\n" -" println!(\"{thread_id:?}: done\");\n" -" });\n" -" thread::sleep(Duration::from_millis(100));\n" -"\n" -" for msg in rx.iter() {\n" -" println!(\"Main: got {msg}\");\n" -" }\n" -"}\n" -"```" -#: src/concurrency/channels/bounded.md:3 -msgid "Bounded and synchronous channels make `send` block the current thread:" +#: src/concurrency/channels/unbounded.md src/concurrency/channels/bounded.md +msgid "\"{thread_id:?}: sent Message {i}\"" +msgstr "" + +#: src/concurrency/channels/unbounded.md src/concurrency/channels/bounded.md +msgid "\"{thread_id:?}: done\"" +msgstr "" + +#: src/concurrency/channels/unbounded.md src/concurrency/channels/bounded.md +msgid "\"Main: got {msg}\"" +msgstr "" + +#: src/concurrency/channels/bounded.md +#, fuzzy +msgid "" +"With bounded (synchronous) channels, `send` can block the current thread:" msgstr "有界限的同步通道可讓 `send` 阻擋現行執行緒:" -#: src/concurrency/channels/bounded.md:5 +#: src/concurrency/channels/bounded.md msgid "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::sync_channel(3);\n" -"\n" -" thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" for i in 1..10 {\n" -" tx.send(format!(\"Message {i}\")).unwrap();\n" -" println!(\"{thread_id:?}: sent Message {i}\");\n" -" }\n" -" println!(\"{thread_id:?}: done\");\n" -" });\n" -" thread::sleep(Duration::from_millis(100));\n" -"\n" -" for msg in rx.iter() {\n" -" println!(\"Main: got {msg}\");\n" -" }\n" -"}\n" -"```" +"Calling `send` will block the current thread until there is space in the " +"channel for the new message. The thread can be blocked indefinitely if there " +"is nobody who reads from the channel." msgstr "" -"```rust,editable\n" -"use std::sync::mpsc;\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"fn main() {\n" -" let (tx, rx) = mpsc::sync_channel(3);\n" -"\n" -" thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" for i in 1..10 {\n" -" tx.send(format!(\"Message {i}\")).unwrap();\n" -" println!(\"{thread_id:?}: sent Message {i}\");\n" -" }\n" -" println!(\"{thread_id:?}: done\");\n" -" });\n" -" thread::sleep(Duration::from_millis(100));\n" -"\n" -" for msg in rx.iter() {\n" -" println!(\"Main: got {msg}\");\n" -" }\n" -"}\n" -"```" -#: src/concurrency/send-sync.md:1 -msgid "`Send` and `Sync`" -msgstr "`Send` 和 `Sync`" - -#: src/concurrency/send-sync.md:3 +#: src/concurrency/channels/bounded.md msgid "" -"How does Rust know to forbid shared access across thread? The answer is in " +"A call to `send` will abort with an error (that is why it returns `Result`) " +"if the channel is closed. A channel is closed when the receiver is dropped." +msgstr "" + +#: src/concurrency/channels/bounded.md +msgid "" +"A bounded channel with a size of zero is called a \"rendezvous channel\". " +"Every send will block the current thread until another thread calls `read`." +msgstr "" + +#: src/concurrency/send-sync.md +#, fuzzy +msgid "" +"How does Rust know to forbid shared access across threads? The answer is in " "two traits:" msgstr "Rust 如何得知要禁止在執行緒間共享存取權?答案就在以下兩個特徵中:" -#: src/concurrency/send-sync.md:5 +#: src/concurrency/send-sync.md msgid "" "[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html): a type `T` " "is `Send` if it is safe to move a `T` across a thread boundary." @@ -17329,7 +19599,7 @@ msgstr "" "[`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html):如果可以將 " "`T` 在執行緒界線間安全轉移,型別 `T` 就會是 `Send`。" -#: src/concurrency/send-sync.md:7 +#: src/concurrency/send-sync.md msgid "" "[`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html): a type `T` " "is `Sync` if it is safe to move a `&T` across a thread boundary." @@ -17337,7 +19607,7 @@ msgstr "" "[`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html):如果可以將 " "`&T` 在執行緒界線間安全轉移,型別 `T` 就會是 `Sync`。" -#: src/concurrency/send-sync.md:10 +#: src/concurrency/send-sync.md msgid "" "`Send` and `Sync` are [unsafe traits](../unsafe/unsafe-traits.md). The " "compiler will automatically derive them for your types as long as they only " @@ -17348,21 +19618,17 @@ msgstr "" "只包含其他有 `Send` 和 `Sync` 的型別, 編譯器就會自動根據型別為你產生 `Send` " "和 `Sync`。或許如果你知道你的型別是適用的, 也可以手動實作。" -#: src/concurrency/send-sync.md:20 +#: src/concurrency/send-sync.md msgid "" "One can think of these traits as markers that the type has certain thread-" "safety properties." msgstr "這些特徵可視為標記,表示該型別含有特定執行緒安全屬性。" -#: src/concurrency/send-sync.md:21 +#: src/concurrency/send-sync.md msgid "They can be used in the generic constraints as normal traits." msgstr "這些特徵就像一般特徵,可用於泛型條件約束。" -#: src/concurrency/send-sync/send.md:1 -msgid "`Send`" -msgstr "`Send`" - -#: src/concurrency/send-sync/send.md:3 +#: src/concurrency/send-sync/send.md msgid "" "A type `T` is [`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html) " "if it is safe to move a `T` value to another thread." @@ -17370,7 +19636,7 @@ msgstr "" "如果可以將 `T` 值安全轉移至其他執行緒,型別 `T` 就會是 [`Send`](https://doc." "rust-lang.org/std/marker/trait.Send.html)。" -#: src/concurrency/send-sync/send.md:5 +#: src/concurrency/send-sync/send.md msgid "" "The effect of moving ownership to another thread is that _destructors_ will " "run in that thread. So the question is when you can allocate a value in one " @@ -17380,17 +19646,13 @@ msgstr "" "問題是,何時能在一個執行緒中配置一個值, 並在另一個執行緒中釋放這個值的記憶" "體。" -#: src/concurrency/send-sync/send.md:13 +#: src/concurrency/send-sync/send.md msgid "" "As an example, a connection to the SQLite library must only be accessed from " "a single thread." msgstr "舉例來說,與 SQLite 資料庫的連線必須只能透過單一執行緒 存取。" -#: src/concurrency/send-sync/sync.md:1 -msgid "`Sync`" -msgstr "`Sync`" - -#: src/concurrency/send-sync/sync.md:3 +#: src/concurrency/send-sync/sync.md msgid "" "A type `T` is [`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html) " "if it is safe to access a `T` value from multiple threads at the same time." @@ -17398,15 +19660,15 @@ msgstr "" "如果可以同時從多個執行緒存取 `T` 值, 型別 `T` 就會是 [`Sync`](https://doc." "rust-lang.org/std/marker/trait.Sync.html)。" -#: src/concurrency/send-sync/sync.md:6 +#: src/concurrency/send-sync/sync.md msgid "More precisely, the definition is:" msgstr "更精確的定義如下:" -#: src/concurrency/send-sync/sync.md:8 +#: src/concurrency/send-sync/sync.md msgid "`T` is `Sync` if and only if `&T` is `Send`" msgstr "`&T` 必須為 `Send`,`T` 才會是 `Sync`" -#: src/concurrency/send-sync/sync.md:14 +#: src/concurrency/send-sync/sync.md msgid "" "This statement is essentially a shorthand way of saying that if a type is " "thread-safe for shared use, it is also thread-safe to pass references of it " @@ -17415,7 +19677,7 @@ msgstr "" "這定義簡單的表示,若一個型別可以在確保執行緒安全的情況下被共用,這型別的參考" "值也可以安全的被傳遞於其他的執行緒。" -#: src/concurrency/send-sync/sync.md:16 +#: src/concurrency/send-sync/sync.md msgid "" "This is because if a type is Sync it means that it can be shared across " "multiple threads without the risk of data races or other synchronization " @@ -17427,116 +19689,117 @@ msgstr "" "題的風險,因此可以安全轉移到其他執行緒。此外,由於可以從任何執行緒安全存取型" "別參考的資料,型別參考也能安全地轉移到其他執行緒。" -#: src/concurrency/send-sync/examples.md:3 +#: src/concurrency/send-sync/examples.md msgid "`Send + Sync`" msgstr "`Send + Sync`" -#: src/concurrency/send-sync/examples.md:5 +#: src/concurrency/send-sync/examples.md msgid "Most types you come across are `Send + Sync`:" msgstr "你遇到的多數型別會是 `Send + Sync`:" -#: src/concurrency/send-sync/examples.md:7 +#: src/concurrency/send-sync/examples.md msgid "`i8`, `f32`, `bool`, `char`, `&str`, ..." msgstr "`i8`、`f32`、`bool`、`char`、`&str`、..." -#: src/concurrency/send-sync/examples.md:8 +#: src/concurrency/send-sync/examples.md msgid "`(T1, T2)`, `[T; N]`, `&[T]`, `struct { x: T }`, ..." msgstr "`(T1, T2)`、`[T; N]`、`&[T]`、`struct { x: T }`、..." -#: src/concurrency/send-sync/examples.md:9 +#: src/concurrency/send-sync/examples.md msgid "`String`, `Option`, `Vec`, `Box`, ..." msgstr "`String`、`Option`、`Vec`、`Box`、..." -#: src/concurrency/send-sync/examples.md:10 +#: src/concurrency/send-sync/examples.md msgid "`Arc`: Explicitly thread-safe via atomic reference count." msgstr "`Arc`:透過原子參考計數明確防護執行緒安全。" -#: src/concurrency/send-sync/examples.md:11 +#: src/concurrency/send-sync/examples.md msgid "`Mutex`: Explicitly thread-safe via internal locking." msgstr "`Mutex`:透過內部鎖定系統明確防護執行緒安全。" -#: src/concurrency/send-sync/examples.md:12 +#: src/concurrency/send-sync/examples.md msgid "`AtomicBool`, `AtomicU8`, ...: Uses special atomic instructions." msgstr "`AtomicBool`、`AtomicU8`、...:使用特殊原子性指示。" -#: src/concurrency/send-sync/examples.md:14 +#: src/concurrency/send-sync/examples.md msgid "" "The generic types are typically `Send + Sync` when the type parameters are " "`Send + Sync`." msgstr "如果型別參數是 `Send + Sync`, 一般型別通常就會是 `Send + Sync`。" -#: src/concurrency/send-sync/examples.md:17 +#: src/concurrency/send-sync/examples.md msgid "`Send + !Sync`" msgstr "`Send + !Sync`" -#: src/concurrency/send-sync/examples.md:19 +#: src/concurrency/send-sync/examples.md msgid "" "These types can be moved to other threads, but they're not thread-safe. " "Typically because of interior mutability:" msgstr "" "以下型別可以轉移到其他執行緒,但不會防護執行緒安全。 原因通常在於內部可變性:" -#: src/concurrency/send-sync/examples.md:22 +#: src/concurrency/send-sync/examples.md msgid "`mpsc::Sender`" msgstr "`mpsc::Sender`" -#: src/concurrency/send-sync/examples.md:23 +#: src/concurrency/send-sync/examples.md msgid "`mpsc::Receiver`" msgstr "`mpsc::Receiver`" -#: src/concurrency/send-sync/examples.md:24 +#: src/concurrency/send-sync/examples.md msgid "`Cell`" msgstr "`Cell`" -#: src/concurrency/send-sync/examples.md:25 +#: src/concurrency/send-sync/examples.md msgid "`RefCell`" msgstr "`RefCell`" -#: src/concurrency/send-sync/examples.md:27 +#: src/concurrency/send-sync/examples.md msgid "`!Send + Sync`" msgstr "`!Send + Sync`" -#: src/concurrency/send-sync/examples.md:29 +#: src/concurrency/send-sync/examples.md msgid "" "These types are thread-safe, but they cannot be moved to another thread:" msgstr "以下型別會防護執行緒安全,但無法轉移至其他執行緒:" -#: src/concurrency/send-sync/examples.md:31 +#: src/concurrency/send-sync/examples.md +#, fuzzy msgid "" -"`MutexGuard`: Uses OS level primitives which must be deallocated on the " -"thread which created them." +"`MutexGuard`: Uses OS level primitives which must be deallocated on " +"the thread which created them." msgstr "" "`MutexGuard`:使用 OS 層級的原始元件,這類元件必須在建立該元件的 執行緒上" "釋放記憶體。" -#: src/concurrency/send-sync/examples.md:34 +#: src/concurrency/send-sync/examples.md msgid "`!Send + !Sync`" msgstr "`!Send + !Sync`" -#: src/concurrency/send-sync/examples.md:36 +#: src/concurrency/send-sync/examples.md msgid "These types are not thread-safe and cannot be moved to other threads:" msgstr "以下型別不會防護執行緒安全,也無法轉移至其他執行緒:" -#: src/concurrency/send-sync/examples.md:38 +#: src/concurrency/send-sync/examples.md msgid "" "`Rc`: each `Rc` has a reference to an `RcBox`, which contains a non-" "atomic reference count." msgstr "" "`Rc`:每個 `Rc` 都有一個 `RcBox` 參考,其中包含一個 非原子參考計數。" -#: src/concurrency/send-sync/examples.md:40 +#: src/concurrency/send-sync/examples.md msgid "" "`*const T`, `*mut T`: Rust assumes raw pointers may have special concurrency " "considerations." msgstr "`*const T`、`*mut T`:Rust 會假定原始指標可能有特殊的 並行考量。" -#: src/concurrency/shared_state.md:3 +#: src/concurrency/shared_state.md msgid "" "Rust uses the type system to enforce synchronization of shared data. This is " "primarily done via two types:" msgstr "Rust 會使用型別系統強制同步共享的資料,主要透過兩種型別 執行:" -#: src/concurrency/shared_state.md:6 +#: src/concurrency/shared_state.md msgid "" "[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html), atomic " "reference counted `T`: handles sharing between threads and takes care to " @@ -17546,7 +19809,7 @@ msgstr "" "為 `T`:處理執行緒間的共享狀態, 並且在最後參考被丟棄時負責釋放 `T` 的記憶" "體。" -#: src/concurrency/shared_state.md:8 +#: src/concurrency/shared_state.md msgid "" "[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html): ensures " "mutually exclusive access to the `T` value." @@ -17554,11 +19817,7 @@ msgstr "" "[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html):確保能提" "供 `T` 值的可變專屬存取權。" -#: src/concurrency/shared_state/arc.md:1 -msgid "`Arc`" -msgstr "`Arc`" - -#: src/concurrency/shared_state/arc.md:3 +#: src/concurrency/shared_state/arc.md msgid "" "[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) allows shared " "read-only access via `Arc::clone`:" @@ -17566,64 +19825,31 @@ msgstr "" "[`Arc`](https://doc.rust-lang.org/std/sync/struct.Arc.html) 可透過 `Arc::" "clone` 取得共享唯讀存取權:" -#: src/concurrency/shared_state/arc.md:5 -msgid "" -"```rust,editable\n" -"use std::thread;\n" -"use std::sync::Arc;\n" -"\n" -"fn main() {\n" -" let v = Arc::new(vec![10, 20, 30]);\n" -" let mut handles = Vec::new();\n" -" for _ in 1..5 {\n" -" let v = Arc::clone(&v);\n" -" handles.push(thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" println!(\"{thread_id:?}: {v:?}\");\n" -" }));\n" -" }\n" -"\n" -" handles.into_iter().for_each(|h| h.join().unwrap());\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" +#: src/concurrency/shared_state/arc.md +msgid "\"{thread_id:?}: {v:?}\"" msgstr "" -"```rust,editable\n" -"use std::thread;\n" -"use std::sync::Arc;\n" -"\n" -"fn main() {\n" -" let v = Arc::new(vec![10, 20, 30]);\n" -" let mut handles = Vec::new();\n" -" for _ in 1..5 {\n" -" let v = Arc::clone(&v);\n" -" handles.push(thread::spawn(move || {\n" -" let thread_id = thread::current().id();\n" -" println!(\"{thread_id:?}: {v:?}\");\n" -" }));\n" -" }\n" -"\n" -" handles.into_iter().for_each(|h| h.join().unwrap());\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" -#: src/concurrency/shared_state/arc.md:29 +#: src/concurrency/shared_state/arc.md src/concurrency/shared_state/example.md +msgid "\"v: {v:?}\"" +msgstr "" + +#: src/concurrency/shared_state/arc.md msgid "" "`Arc` stands for \"Atomic Reference Counted\", a thread safe version of `Rc` " "that uses atomic operations." msgstr "" "`Arc` 代表「原子參考計數」,這個 `Rc` 的執行緒安全版本會採用原子性 運算。" -#: src/concurrency/shared_state/arc.md:31 +#: src/concurrency/shared_state/arc.md +#, fuzzy msgid "" "`Arc` implements `Clone` whether or not `T` does. It implements `Send` " -"and `Sync` iff `T` implements them both." +"and `Sync` if and only if `T` implements them both." msgstr "" "`Arc` 會實作 `Clone`,與 `T` 無關。如果 `T` 同時實作 `Send` 和 `Sync`, " "`Arc` 也會實作這兩者。" -#: src/concurrency/shared_state/arc.md:33 +#: src/concurrency/shared_state/arc.md msgid "" "`Arc::clone()` has the cost of atomic operations that get executed, but " "after that the use of the `T` is free." @@ -17631,64 +19857,32 @@ msgstr "" "`Arc::clone()` 會導致執行原子性運算的費用,但之後使用得到的 `T` 不需任何費" "用。" -#: src/concurrency/shared_state/arc.md:35 +#: src/concurrency/shared_state/arc.md msgid "" "Beware of reference cycles, `Arc` does not use a garbage collector to detect " "them." msgstr "留意參考循環,`Arc` 並不使用垃圾收集器進行偵測。" -#: src/concurrency/shared_state/arc.md:36 +#: src/concurrency/shared_state/arc.md msgid "`std::sync::Weak` can help." msgstr "`std::sync::Weak` 可協助執行這項功能。" -#: src/concurrency/shared_state/mutex.md:1 -msgid "`Mutex`" -msgstr "`Mutex`" - -#: src/concurrency/shared_state/mutex.md:3 +#: src/concurrency/shared_state/mutex.md +#, fuzzy msgid "" "[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) ensures " "mutual exclusion _and_ allows mutable access to `T` behind a read-only " -"interface:" +"interface (another form of [interior mutability](../../borrowing/interior-" +"mutability)):" msgstr "" "[`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) 可確保執行" "互斥功能,「並」在唯讀介面背後授予 `T` 的可變存取權:" -#: src/concurrency/shared_state/mutex.md:6 -msgid "" -"```rust,editable\n" -"use std::sync::Mutex;\n" -"\n" -"fn main() {\n" -" let v = Mutex::new(vec![10, 20, 30]);\n" -" println!(\"v: {:?}\", v.lock().unwrap());\n" -"\n" -" {\n" -" let mut guard = v.lock().unwrap();\n" -" guard.push(40);\n" -" }\n" -"\n" -" println!(\"v: {:?}\", v.lock().unwrap());\n" -"}\n" -"```" +#: src/concurrency/shared_state/mutex.md +msgid "\"v: {:?}\"" msgstr "" -"```rust,editable\n" -"use std::sync::Mutex;\n" -"\n" -"fn main() {\n" -" let v = Mutex::new(vec![10, 20, 30]);\n" -" println!(\"v: {:?}\", v.lock().unwrap());\n" -"\n" -" {\n" -" let mut guard = v.lock().unwrap();\n" -" guard.push(40);\n" -" }\n" -"\n" -" println!(\"v: {:?}\", v.lock().unwrap());\n" -"}\n" -"```" -#: src/concurrency/shared_state/mutex.md:22 +#: src/concurrency/shared_state/mutex.md msgid "" "Notice how we have a [`impl Sync for Mutex`](https://doc.rust-" "lang.org/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E) blanket " @@ -17697,19 +19891,20 @@ msgstr "" "請留意我們如何進行 [`impl Sync for Mutex`](https://doc.rust-lang." "org/std/sync/struct.Mutex.html#impl-Sync-for-Mutex%3CT%3E) 的概括性 實作。" -#: src/concurrency/shared_state/mutex.md:31 +#: src/concurrency/shared_state/mutex.md +#, fuzzy msgid "" -"`Mutex` in Rust looks like a collection with just one element - the " +"`Mutex` in Rust looks like a collection with just one element --- the " "protected data." msgstr "Rust 中的 `Mutex` 就像是只有一個元素的集合,也就是受保護的資料。" -#: src/concurrency/shared_state/mutex.md:32 +#: src/concurrency/shared_state/mutex.md msgid "" "It is not possible to forget to acquire the mutex before accessing the " "protected data." msgstr "必須先取得互斥鎖,才能存取受保護的資料。" -#: src/concurrency/shared_state/mutex.md:33 +#: src/concurrency/shared_state/mutex.md msgid "" "You can get an `&mut T` from an `&Mutex` by taking the lock. The " "`MutexGuard` ensures that the `&mut T` doesn't outlive the lock being held." @@ -17717,19 +19912,24 @@ msgstr "" "只要使用這個鎖,就能從 `&Mutex` 取得 `&mut T`。`MutexGuard` 可確保 `&mut " "T` 的壽命不會超過所持有的鎖。" -#: src/concurrency/shared_state/mutex.md:35 -msgid "`Mutex` implements both `Send` and `Sync` iff `T` implements `Send`." +#: src/concurrency/shared_state/mutex.md +#, fuzzy +msgid "" +"`Mutex` implements both `Send` and `Sync` iff (if and only if) `T` " +"implements `Send`." msgstr "如果 `T` 實作 `Send`,`Mutex` 才會實作 `Send` 和 `Sync`。" -#: src/concurrency/shared_state/mutex.md:36 -msgid "A read-write lock counterpart - `RwLock`." +#: src/concurrency/shared_state/mutex.md +#, fuzzy +msgid "A read-write lock counterpart: `RwLock`." msgstr "可讀寫的對應鎖 - `RwLock`。" -#: src/concurrency/shared_state/mutex.md:37 -msgid "Why does `lock()` return a `Result`? " +#: src/concurrency/shared_state/mutex.md +#, fuzzy +msgid "Why does `lock()` return a `Result`?" msgstr "為何 `lock()` 會傳回 `Result`?" -#: src/concurrency/shared_state/mutex.md:38 +#: src/concurrency/shared_state/mutex.md msgid "" "If the thread that held the `Mutex` panicked, the `Mutex` becomes " "\"poisoned\" to signal that the data it protected might be in an " @@ -17742,115 +19942,35 @@ msgstr "" "[`PoisonError`](https://doc.rust-lang.org/std/sync/struct.PoisonError.html) " "錯誤。無論如何,你都可以對錯誤呼叫 `into_inner()` 來復原 資料。" -#: src/concurrency/shared_state/example.md:3 +#: src/concurrency/shared_state/example.md msgid "Let us see `Arc` and `Mutex` in action:" msgstr "我們來看看 `Arc` 和 `Mutex` 的實際應用情形:" -#: src/concurrency/shared_state/example.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"use std::thread;\n" -"// use std::sync::{Arc, Mutex};\n" -"\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let handle = thread::spawn(|| {\n" -" v.push(10);\n" -" });\n" -" v.push(1000);\n" -"\n" -" handle.join().unwrap();\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" +#: src/concurrency/shared_state/example.md +msgid "// use std::sync::{Arc, Mutex};\n" msgstr "" -"```rust,editable,compile_fail\n" -"use std::thread;\n" -"// use std::sync::{Arc, Mutex};\n" -"\n" -"fn main() {\n" -" let v = vec![10, 20, 30];\n" -" let handle = thread::spawn(|| {\n" -" v.push(10);\n" -" });\n" -" v.push(1000);\n" -"\n" -" handle.join().unwrap();\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" -#: src/concurrency/shared_state/example.md:23 +#: src/concurrency/shared_state/example.md msgid "Possible solution:" msgstr "可能的解決方案:" -#: src/concurrency/shared_state/example.md:25 -msgid "" -"```rust,editable\n" -"use std::sync::{Arc, Mutex};\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let v = Arc::new(Mutex::new(vec![10, 20, 30]));\n" -"\n" -" let v2 = Arc::clone(&v);\n" -" let handle = thread::spawn(move || {\n" -" let mut v2 = v2.lock().unwrap();\n" -" v2.push(10);\n" -" });\n" -"\n" -" {\n" -" let mut v = v.lock().unwrap();\n" -" v.push(1000);\n" -" }\n" -"\n" -" handle.join().unwrap();\n" -"\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" -msgstr "" -"```rust,editable\n" -"use std::sync::{Arc, Mutex};\n" -"use std::thread;\n" -"\n" -"fn main() {\n" -" let v = Arc::new(Mutex::new(vec![10, 20, 30]));\n" -"\n" -" let v2 = Arc::clone(&v);\n" -" let handle = thread::spawn(move || {\n" -" let mut v2 = v2.lock().unwrap();\n" -" v2.push(10);\n" -" });\n" -"\n" -" {\n" -" let mut v = v.lock().unwrap();\n" -" v.push(1000);\n" -" }\n" -"\n" -" handle.join().unwrap();\n" -"\n" -" println!(\"v: {v:?}\");\n" -"}\n" -"```" - -#: src/concurrency/shared_state/example.md:49 +#: src/concurrency/shared_state/example.md msgid "Notable parts:" msgstr "重要部分:" -#: src/concurrency/shared_state/example.md:51 +#: src/concurrency/shared_state/example.md msgid "" "`v` is wrapped in both `Arc` and `Mutex`, because their concerns are " "orthogonal." msgstr "`v` 已同時納入 `Arc` 和 `Mutex`,因為兩者的考量互不相關。" -#: src/concurrency/shared_state/example.md:52 +#: src/concurrency/shared_state/example.md msgid "" "Wrapping a `Mutex` in an `Arc` is a common pattern to share mutable state " "between threads." msgstr "將 `Mutex` 納入 `Arc`,是在執行緒間共享可變狀態的常見模式。" -#: src/concurrency/shared_state/example.md:53 +#: src/concurrency/shared_state/example.md msgid "" "`v: Arc<_>` needs to be cloned as `v2` before it can be moved into another " "thread. Note `move` was added to the lambda signature." @@ -17858,31 +19978,31 @@ msgstr "" "`v: Arc<_>` 需要複製成 `v2`,才能轉移到其他執行緒。請注意,`move` 已新增至 " "lambda 簽章。" -#: src/concurrency/shared_state/example.md:54 +#: src/concurrency/shared_state/example.md msgid "" "Blocks are introduced to narrow the scope of the `LockGuard` as much as " "possible." msgstr "采用區塊,盡量縮小 `LockGuard` 的範圍。" -#: src/exercises/concurrency/morning.md:3 +#: src/exercises/concurrency/morning.md msgid "Let us practice our new concurrency skills with" msgstr "" -#: src/exercises/concurrency/morning.md:5 +#: src/exercises/concurrency/morning.md msgid "Dining philosophers: a classic problem in concurrency." msgstr "" -#: src/exercises/concurrency/morning.md:7 +#: src/exercises/concurrency/morning.md msgid "" "Multi-threaded link checker: a larger project where you'll use Cargo to " "download dependencies and then check links in parallel." msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:3 +#: src/exercises/concurrency/dining-philosophers.md msgid "The dining philosophers problem is a classic problem in concurrency:" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:5 +#: src/exercises/concurrency/dining-philosophers.md msgid "" "Five philosophers dine together at the same table. Each philosopher has " "their own place at the table. There is a fork between each plate. The dish " @@ -17894,63 +20014,102 @@ msgid "" "down both forks." msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:13 +#: src/exercises/concurrency/dining-philosophers.md msgid "" "You will need a local [Cargo installation](../../cargo/running-locally.md) " "for this exercise. Copy the code below to a file called `src/main.rs`, fill " "out the blanks, and test that `cargo run` does not deadlock:" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:19 +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/dining-philosophers-async.md msgid "" -"```rust,compile_fail\n" -"use std::sync::{mpsc, Arc, Mutex};\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"struct Fork;\n" -"\n" -"struct Philosopher {\n" -" name: String,\n" -" // left_fork: ...\n" +"// left_fork: ...\n" " // right_fork: ...\n" " // thoughts: ...\n" -"}\n" -"\n" -"impl Philosopher {\n" -" fn think(&self) {\n" -" self.thoughts\n" -" .send(format!(\"Eureka! {} has a new idea!\", &self.name))\n" -" .unwrap();\n" -" }\n" -"\n" -" fn eat(&self) {\n" -" // Pick up forks...\n" -" println!(\"{} is eating...\", &self.name);\n" -" thread::sleep(Duration::from_millis(10));\n" -" }\n" -"}\n" -"\n" -"static PHILOSOPHERS: &[&str] =\n" -" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" -"\n" -"fn main() {\n" -" // Create forks\n" -"\n" -" // Create philosophers\n" -"\n" -" // Make them think and eat\n" -"\n" -" // Output their thoughts\n" -"}\n" -"```" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:61 +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Eureka! {} has a new idea!\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Pick up forks...\n" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"{} is eating...\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Socrates\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Hypatia\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Plato\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Aristotle\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/solutions-morning.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Pythagoras\"" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Create forks\n" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Create philosophers\n" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +msgid "// Make each of them think and eat 100 times\n" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Output their thoughts\n" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers.md msgid "You can use the following `Cargo.toml`:" msgstr "" -#: src/exercises/concurrency/dining-philosophers.md:65 +#: src/exercises/concurrency/dining-philosophers.md msgid "" "```toml\n" "[package]\n" @@ -17960,7 +20119,7 @@ msgid "" "```" msgstr "" -#: src/exercises/concurrency/link-checker.md:3 +#: src/exercises/concurrency/link-checker.md msgid "" "Let us use our new knowledge to create a multi-threaded link checker. It " "should start at a webpage and check that links on the page are valid. It " @@ -17968,59 +20127,36 @@ msgid "" "until all pages have been validated." msgstr "" -#: src/exercises/concurrency/link-checker.md:8 +#: src/exercises/concurrency/link-checker.md msgid "" "For this, you will need an HTTP client such as [`reqwest`](https://docs.rs/" "reqwest/). Create a new Cargo project and `reqwest` it as a dependency with:" msgstr "" -#: src/exercises/concurrency/link-checker.md:11 -msgid "" -"```shell\n" -"$ cargo new link-checker\n" -"$ cd link-checker\n" -"$ cargo add --features blocking,rustls-tls reqwest\n" -"```" -msgstr "" - -#: src/exercises/concurrency/link-checker.md:17 +#: src/exercises/concurrency/link-checker.md msgid "" "If `cargo add` fails with `error: no such subcommand`, then please edit the " "`Cargo.toml` file by hand. Add the dependencies listed below." msgstr "" -#: src/exercises/concurrency/link-checker.md:20 +#: src/exercises/concurrency/link-checker.md msgid "" "You will also need a way to find links. We can use [`scraper`](https://docs." "rs/scraper/) for that:" msgstr "" -#: src/exercises/concurrency/link-checker.md:22 -msgid "" -"```shell\n" -"$ cargo add scraper\n" -"```" -msgstr "" - -#: src/exercises/concurrency/link-checker.md:26 +#: src/exercises/concurrency/link-checker.md msgid "" "Finally, we'll need some way of handling errors. We use [`thiserror`]" "(https://docs.rs/thiserror/) for that:" msgstr "" -#: src/exercises/concurrency/link-checker.md:29 -msgid "" -"```shell\n" -"$ cargo add thiserror\n" -"```" -msgstr "" - -#: src/exercises/concurrency/link-checker.md:33 +#: src/exercises/concurrency/link-checker.md msgid "" "The `cargo add` calls will update the `Cargo.toml` file to look like this:" msgstr "" -#: src/exercises/concurrency/link-checker.md:37 +#: src/exercises/concurrency/link-checker.md msgid "" "```toml\n" "[package]\n" @@ -18037,92 +20173,130 @@ msgid "" "```" msgstr "" -#: src/exercises/concurrency/link-checker.md:50 +#: src/exercises/concurrency/link-checker.md msgid "" "You can now download the start page. Try with a small site such as `https://" "www.google.org/`." msgstr "" -#: src/exercises/concurrency/link-checker.md:53 +#: src/exercises/concurrency/link-checker.md msgid "Your `src/main.rs` file should look something like this:" msgstr "" -#: src/exercises/concurrency/link-checker.md:57 -msgid "" -"```rust,compile_fail\n" -"use reqwest::blocking::{get, Response};\n" -"use reqwest::Url;\n" -"use scraper::{Html, Selector};\n" -"use thiserror::Error;\n" -"\n" -"#[derive(Error, Debug)]\n" -"enum Error {\n" -" #[error(\"request error: {0}\")]\n" -" ReqwestError(#[from] reqwest::Error),\n" -"}\n" -"\n" -"fn extract_links(response: Response) -> Result, Error> {\n" -" let base_url = response.url().to_owned();\n" -" let document = response.text()?;\n" -" let html = Html::parse_document(&document);\n" -" let selector = Selector::parse(\"a\").unwrap();\n" -"\n" -" let mut valid_urls = Vec::new();\n" -" for element in html.select(&selector) {\n" -" if let Some(href) = element.value().attr(\"href\") {\n" -" match base_url.join(href) {\n" -" Ok(url) => valid_urls.push(url),\n" -" Err(err) => {\n" -" println!(\"On {base_url}: could not parse {href:?}: " -"{err} (ignored)\",);\n" -" }\n" -" }\n" -" }\n" -" }\n" -"\n" -" Ok(valid_urls)\n" -"}\n" -"\n" -"fn main() {\n" -" let start_url = Url::parse(\"https://www.google.org\").unwrap();\n" -" let response = get(start_url).unwrap();\n" -" match extract_links(response) {\n" -" Ok(links) => println!(\"Links: {links:#?}\"),\n" -" Err(err) => println!(\"Could not extract links: {err:#}\"),\n" -" }\n" -"}\n" -"```" +#: src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"request error: {0}\"" msgstr "" -#: src/exercises/concurrency/link-checker.md:100 +#: src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"bad http response: {0}\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"Checking {:#}\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"href\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"On {base_url:#}: ignored unparsable {href:?}: {err}\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md +#: src/exercises/concurrency/solutions-morning.md +msgid "\"https://www.google.org\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md +msgid "\"Links: {links:#?}\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md +msgid "\"Could not extract links: {err:#}\"" +msgstr "" + +#: src/exercises/concurrency/link-checker.md msgid "Run the code in `src/main.rs` with" msgstr "" -#: src/exercises/concurrency/link-checker.md:102 -msgid "" -"```shell\n" -"$ cargo run\n" -"```" -msgstr "" - -#: src/exercises/concurrency/link-checker.md:108 +#: src/exercises/concurrency/link-checker.md msgid "" "Use threads to check the links in parallel: send the URLs to be checked to a " "channel and let a few threads check the URLs in parallel." msgstr "" -#: src/exercises/concurrency/link-checker.md:110 +#: src/exercises/concurrency/link-checker.md msgid "" "Extend this to recursively extract links from all pages on the `www.google." "org` domain. Put an upper limit of 100 pages or so so that you don't end up " "being blocked by the site." msgstr "" -#: src/async.md:1 +#: src/exercises/concurrency/solutions-morning.md +msgid "Concurrency Morning Exercise" +msgstr "並行:上午練習" + +#: src/exercises/concurrency/solutions-morning.md +msgid "([back to exercise](dining-philosophers.md))" +msgstr "([返回練習](dining-philosophers.md))" + +#: src/exercises/concurrency/solutions-morning.md +msgid "\"{} is trying to eat\"" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "" +"// To avoid a deadlock, we have to break the symmetry\n" +" // somewhere. This will swap the forks without deinitializing\n" +" // either of them.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "\"{thought}\"" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "Link Checker" +msgstr "連結檢查器" + +#: src/exercises/concurrency/solutions-morning.md +msgid "([back to exercise](link-checker.md))" +msgstr "([返回練習](link-checker.md))" + +#: src/exercises/concurrency/solutions-morning.md +msgid "" +"/// Determine whether links within the given page should be extracted.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "" +"/// Mark the given page as visited, returning false if it had already\n" +" /// been visited.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "// The sender got dropped. No more commands coming in.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "\"Got crawling error: {:#}\"" +msgstr "" + +#: src/exercises/concurrency/solutions-morning.md +msgid "\"Bad URLs: {:#?}\"" +msgstr "" + +#: src/async.md msgid "Async Rust" msgstr "非同步的 Rust" -#: src/async.md:3 +#: src/async.md msgid "" "\"Async\" is a concurrency model where multiple tasks are executed " "concurrently by executing each task until it would block, then switching to " @@ -18136,7 +20310,7 @@ msgstr "" "量有限的環境下執行大量的任務,這是因為每個任務所造成的開銷通常都很低,而且作" "業系統提供的基本功能能夠有效地辨識可處理的 I/O。" -#: src/async.md:10 +#: src/async.md msgid "" "Rust's asynchronous operation is based on \"futures\", which represent work " "that may be completed in the future. Futures are \"polled\" until they " @@ -18145,17 +20319,13 @@ msgstr "" "Rust 的非同步操作是透過「future」來處理,代表可能在未來完成的工作。Future 會" "處在被「輪詢(poll)」的狀態,直到它送出信號來表示工作已經處理完成。" -#: src/async.md:14 +#: src/async.md msgid "" "Futures are polled by an async runtime, and several different runtimes are " "available." msgstr "Future 會被非同步的執行環境(runtime)輪詢,而執行環境有許多種可選擇。" -#: src/async.md:17 -msgid "Comparisons" -msgstr "比較" - -#: src/async.md:19 +#: src/async.md msgid "" "Python has a similar model in its `asyncio`. However, its `Future` type is " "callback-based, and not polled. Async Python programs require a \"loop\", " @@ -18165,7 +20335,7 @@ msgstr "" "函數(callback)而非輪詢。非同步的 Python 程式需要「迴圈(loop)」來處理,類" "似於 Rust 的執行環境。" -#: src/async.md:23 +#: src/async.md msgid "" "JavaScript's `Promise` is similar, but again callback-based. The language " "runtime implements the event loop, so many of the details of Promise " @@ -18174,39 +20344,18 @@ msgstr "" "JavaScript 的 `Promise` 也是類似的概念,但仍是基於回呼函數。JavaScript 的語言" "執行環境實作了事件迴圈(event loop),所以隱藏了很多關於 Promise 的處理細節。" -#: src/async/async-await.md:1 -msgid "`async`/`await`" -msgstr "`async`/`await`" - -#: src/async/async-await.md:3 +#: src/async/async-await.md msgid "" "At a high level, async Rust code looks very much like \"normal\" sequential " "code:" msgstr "" "從高層次的角度來看,非同步的 Rust 程式碼看起來很像「一般的」同步程式碼:" -#: src/async/async-await.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"use futures::executor::block_on;\n" -"\n" -"async fn count_to(count: i32) {\n" -" for i in 1..=count {\n" -" println!(\"Count is: {i}!\");\n" -" }\n" -"}\n" -"\n" -"async fn async_main(count: i32) {\n" -" count_to(count).await;\n" -"}\n" -"\n" -"fn main() {\n" -" block_on(async_main(10));\n" -"}\n" -"```" +#: src/async/async-await.md +msgid "\"Count is: {i}!\"" msgstr "" -#: src/async/async-await.md:27 +#: src/async/async-await.md msgid "" "Note that this is a simplified example to show the syntax. There is no long " "running operation or any real concurrency in it!" @@ -18214,22 +20363,23 @@ msgstr "" "注意這只是一個簡化過的程式碼,目的是要示範程式語法。這份範例程式碼當中並沒有" "需要長時間運行的操作,也沒有真正的併行處理!" -#: src/async/async-await.md:30 +#: src/async/async-await.md msgid "What is the return type of an async call?" msgstr "如何得知非同步函數的回傳型別?" -#: src/async/async-await.md:31 +#: src/async/async-await.md msgid "Use `let future: () = async_main(10);` in `main` to see the type." msgstr "在 `main` 函數中使用 `let feature: () = async_main(10);` 以查看型態。" -#: src/async/async-await.md:33 +#: src/async/async-await.md +#, fuzzy msgid "" "The \"async\" keyword is syntactic sugar. The compiler replaces the return " -"type with a future. " +"type with a future." msgstr "" "「async」這個關鍵字只是個程式碼語法糖。編譯器會將函數回傳型態以 future 取代。" -#: src/async/async-await.md:36 +#: src/async/async-await.md msgid "" "You cannot make `main` async, without additional instructions to the " "compiler on how to use the returned future." @@ -18237,15 +20387,16 @@ msgstr "" "你不能把 `main` 函數標示成非同步函數,除非你對編譯器額外設定了如何處理回傳的 " "future 的方式。" -#: src/async/async-await.md:39 +#: src/async/async-await.md +#, fuzzy msgid "" "You need an executor to run async code. `block_on` blocks the current thread " -"until the provided future has run to completion. " +"until the provided future has run to completion." msgstr "" "你需要處理器去執行非同步的程式碼。`block_on` 會阻塞當前的執行緒,直到 future " "已執行完畢。" -#: src/async/async-await.md:42 +#: src/async/async-await.md msgid "" "`.await` asynchronously waits for the completion of another operation. " "Unlike `block_on`, `.await` doesn't block the current thread." @@ -18253,13 +20404,14 @@ msgstr "" "`.await` 會非同步地等待其他操作執行完畢。別於 `block_on`,`.await` 不會阻塞當" "前的執行緒。" -#: src/async/async-await.md:45 +#: src/async/async-await.md +#, fuzzy msgid "" "`.await` can only be used inside an `async` function (or block; these are " -"introduced later). " +"introduced later)." msgstr "`.await` 只能用在 `async` 函數(或程式碼區塊,之後會介紹)中。" -#: src/async/futures.md:3 +#: src/async/futures.md msgid "" "[`Future`](https://doc.rust-lang.org/std/future/trait.Future.html) is a " "trait, implemented by objects that represent an operation that may not be " @@ -18267,26 +20419,7 @@ msgid "" "doc.rust-lang.org/std/task/enum.Poll.html)." msgstr "" -#: src/async/futures.md:8 -msgid "" -"```rust\n" -"use std::pin::Pin;\n" -"use std::task::Context;\n" -"\n" -"pub trait Future {\n" -" type Output;\n" -" fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll;\n" -"}\n" -"\n" -"pub enum Poll {\n" -" Ready(T),\n" -" Pending,\n" -"}\n" -"```" -msgstr "" - -#: src/async/futures.md:23 +#: src/async/futures.md msgid "" "An async function returns an `impl Future`. It's also possible (but " "uncommon) to implement `Future` for your own types. For example, the " @@ -18294,76 +20427,76 @@ msgid "" "joining to it." msgstr "" -#: src/async/futures.md:27 +#: src/async/futures.md msgid "" "The `.await` keyword, applied to a Future, causes the current async function " "to pause until that Future is ready, and then evaluates to its output." msgstr "" -#: src/async/futures.md:32 +#: src/async/futures.md msgid "" "The `Future` and `Poll` types are implemented exactly as shown; click the " "links to show the implementations in the docs." msgstr "" -#: src/async/futures.md:35 +#: src/async/futures.md msgid "" "We will not get to `Pin` and `Context`, as we will focus on writing async " "code, rather than building new async primitives. Briefly:" msgstr "" -#: src/async/futures.md:38 +#: src/async/futures.md msgid "" "`Context` allows a Future to schedule itself to be polled again when an " "event occurs." msgstr "" -#: src/async/futures.md:41 +#: src/async/futures.md msgid "" "`Pin` ensures that the Future isn't moved in memory, so that pointers into " "that future remain valid. This is required to allow references to remain " "valid after an `.await`." msgstr "" -#: src/async/runtimes.md:3 +#: src/async/runtimes.md msgid "" "A _runtime_ provides support for performing operations asynchronously (a " "_reactor_) and is responsible for executing futures (an _executor_). Rust " "does not have a \"built-in\" runtime, but several options are available:" msgstr "" -#: src/async/runtimes.md:7 +#: src/async/runtimes.md msgid "" -"[Tokio](https://tokio.rs/) - performant, with a well-developed ecosystem of " +"[Tokio](https://tokio.rs/): performant, with a well-developed ecosystem of " "functionality like [Hyper](https://hyper.rs/) for HTTP or [Tonic](https://" "github.com/hyperium/tonic) for gRPC." msgstr "" -#: src/async/runtimes.md:10 +#: src/async/runtimes.md msgid "" -"[async-std](https://async.rs/) - aims to be a \"std for async\", and " -"includes a basic runtime in `async::task`." +"[async-std](https://async.rs/): aims to be a \"std for async\", and includes " +"a basic runtime in `async::task`." msgstr "" -#: src/async/runtimes.md:12 -msgid "[smol](https://docs.rs/smol/latest/smol/) - simple and lightweight" +#: src/async/runtimes.md +msgid "[smol](https://docs.rs/smol/latest/smol/): simple and lightweight" msgstr "" -#: src/async/runtimes.md:14 +#: src/async/runtimes.md msgid "" "Several larger applications have their own runtimes. For example, [Fuchsia]" "(https://fuchsia.googlesource.com/fuchsia/+/refs/heads/main/src/lib/fuchsia-" "async/src/lib.rs) already has one." msgstr "" -#: src/async/runtimes.md:20 +#: src/async/runtimes.md msgid "" "Note that of the listed runtimes, only Tokio is supported in the Rust " "playground. The playground also does not permit any I/O, so most interesting " "async things can't run in the playground." msgstr "" -#: src/async/runtimes.md:24 +#: src/async/runtimes.md msgid "" "Futures are \"inert\" in that they do not do anything (not even start an I/O " "operation) unless there is an executor polling them. This differs from JS " @@ -18371,84 +20504,66 @@ msgid "" "used." msgstr "" -#: src/async/runtimes/tokio.md:4 -msgid "Tokio provides: " +#: src/async/runtimes/tokio.md +msgid "Tokio provides:" msgstr "" -#: src/async/runtimes/tokio.md:6 +#: src/async/runtimes/tokio.md msgid "A multi-threaded runtime for executing asynchronous code." msgstr "" -#: src/async/runtimes/tokio.md:7 +#: src/async/runtimes/tokio.md msgid "An asynchronous version of the standard library." msgstr "" -#: src/async/runtimes/tokio.md:8 +#: src/async/runtimes/tokio.md msgid "A large ecosystem of libraries." msgstr "" -#: src/async/runtimes/tokio.md:10 -msgid "" -"```rust,editable,compile_fail\n" -"use tokio::time;\n" -"\n" -"async fn count_to(count: i32) {\n" -" for i in 1..=count {\n" -" println!(\"Count in task: {i}!\");\n" -" time::sleep(time::Duration::from_millis(5)).await;\n" -" }\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" tokio::spawn(count_to(10));\n" -"\n" -" for i in 1..5 {\n" -" println!(\"Main task: {i}\");\n" -" time::sleep(time::Duration::from_millis(5)).await;\n" -" }\n" -"}\n" -"```" +#: src/async/runtimes/tokio.md +msgid "\"Count in task: {i}!\"" msgstr "" -#: src/async/runtimes/tokio.md:33 +#: src/async/runtimes/tokio.md +msgid "\"Main task: {i}\"" +msgstr "" + +#: src/async/runtimes/tokio.md msgid "With the `tokio::main` macro we can now make `main` async." msgstr "" -#: src/async/runtimes/tokio.md:35 +#: src/async/runtimes/tokio.md msgid "The `spawn` function creates a new, concurrent \"task\"." msgstr "" -#: src/async/runtimes/tokio.md:37 +#: src/async/runtimes/tokio.md msgid "Note: `spawn` takes a `Future`, you don't call `.await` on `count_to`." msgstr "" -#: src/async/runtimes/tokio.md:39 +#: src/async/runtimes/tokio.md msgid "**Further exploration:**" msgstr "" -#: src/async/runtimes/tokio.md:41 +#: src/async/runtimes/tokio.md msgid "" "Why does `count_to` not (usually) get to 10? This is an example of async " "cancellation. `tokio::spawn` returns a handle which can be awaited to wait " "until it finishes." msgstr "" -#: src/async/runtimes/tokio.md:45 +#: src/async/runtimes/tokio.md msgid "Try `count_to(10).await` instead of spawning." msgstr "" -#: src/async/runtimes/tokio.md:47 +#: src/async/runtimes/tokio.md msgid "Try awaiting the task returned from `tokio::spawn`." msgstr "" -#: src/async/tasks.md:3 -msgid "" -"Runtimes have the concept of a \"task\", similar to a thread but much less " -"resource-intensive." +#: src/async/tasks.md +msgid "Rust has a task system, which is a form of lightweight threading." msgstr "" -#: src/async/tasks.md:6 +#: src/async/tasks.md msgid "" "A task has a single top-level future which the executor polls to make " "progress. That future may have one or more nested futures that its `poll` " @@ -18457,210 +20572,170 @@ msgid "" "and an I/O operation." msgstr "" -#: src/async/tasks.md:11 -msgid "" -"```rust,compile_fail\n" -"use tokio::io::{self, AsyncReadExt, AsyncWriteExt};\n" -"use tokio::net::TcpListener;\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> io::Result<()> {\n" -" let listener = TcpListener::bind(\"127.0.0.1:6142\").await?;\n" -"\tprintln!(\"listening on port 6142\");\n" -"\n" -" loop {\n" -" let (mut socket, addr) = listener.accept().await?;\n" -"\n" -" println!(\"connection from {addr:?}\");\n" -"\n" -" tokio::spawn(async move {\n" -" if let Err(e) = socket.write_all(b\"Who are you?\\n\").await {\n" -" println!(\"socket error: {e:?}\");\n" -" return;\n" -" }\n" -"\n" -" let mut buf = vec![0; 1024];\n" -" let reply = match socket.read(&mut buf).await {\n" -" Ok(n) => {\n" -" let name = std::str::from_utf8(&buf[..n]).unwrap()." -"trim();\n" -" format!(\"Thanks for dialing in, {name}!\\n\")\n" -" }\n" -" Err(e) => {\n" -" println!(\"socket error: {e:?}\");\n" -" return;\n" -" }\n" -" };\n" -"\n" -" if let Err(e) = socket.write_all(reply.as_bytes()).await {\n" -" println!(\"socket error: {e:?}\");\n" -" }\n" -" });\n" -" }\n" -"}\n" -"```" +#: src/async/tasks.md +msgid "\"127.0.0.1:0\"" msgstr "" -#: src/async/tasks.md:53 src/async/control-flow/join.md:36 +#: src/async/tasks.md +msgid "\"listening on port {}\"" +msgstr "" + +#: src/async/tasks.md +msgid "\"connection from {addr:?}\"" +msgstr "" + +#: src/async/tasks.md +msgid "b\"Who are you?\\n\"" +msgstr "" + +#: src/async/tasks.md +msgid "\"socket error\"" +msgstr "" + +#: src/async/tasks.md +msgid "\"Thanks for dialing in, {name}!\\n\"" +msgstr "" + +#: src/async/tasks.md src/async/control-flow/join.md msgid "" "Copy this example into your prepared `src/main.rs` and run it from there." msgstr "" -#: src/async/tasks.md:55 +#: src/async/tasks.md +msgid "" +"Try connecting to it with a TCP connection tool like [nc](https://www.unix." +"com/man-page/linux/1/nc/) or [telnet](https://www.unix.com/man-page/linux/1/" +"telnet/)." +msgstr "" + +#: src/async/tasks.md msgid "" "Ask students to visualize what the state of the example server would be with " "a few connected clients. What tasks exist? What are their Futures?" msgstr "" -#: src/async/tasks.md:58 +#: src/async/tasks.md msgid "" "This is the first time we've seen an `async` block. This is similar to a " "closure, but does not take any arguments. Its return value is a Future, " -"similar to an `async fn`. " +"similar to an `async fn`." msgstr "" -#: src/async/tasks.md:62 +#: src/async/tasks.md msgid "" "Refactor the async block into a function, and improve the error handling " "using `?`." msgstr "" -#: src/async/channels.md:3 +#: src/async/channels.md msgid "" -"Several crates have support for `async`/`await`. For instance `tokio` " -"channels:" +"Several crates have support for asynchronous channels. For instance `tokio`:" msgstr "" -#: src/async/channels.md:5 -msgid "" -"```rust,editable,compile_fail\n" -"use tokio::sync::mpsc::{self, Receiver};\n" -"\n" -"async fn ping_handler(mut input: Receiver<()>) {\n" -" let mut count: usize = 0;\n" -"\n" -" while let Some(_) = input.recv().await {\n" -" count += 1;\n" -" println!(\"Received {count} pings so far.\");\n" -" }\n" -"\n" -" println!(\"ping_handler complete\");\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let (sender, receiver) = mpsc::channel(32);\n" -" let ping_handler_task = tokio::spawn(ping_handler(receiver));\n" -" for i in 0..10 {\n" -" sender.send(()).await.expect(\"Failed to send ping.\");\n" -" println!(\"Sent {} pings so far.\", i + 1);\n" -" }\n" -"\n" -" std::mem::drop(sender);\n" -" ping_handler_task.await.expect(\"Something went wrong in ping handler " -"task.\");\n" -"}\n" -"```" +#: src/async/channels.md +msgid "\"Received {count} pings so far.\"" msgstr "" -#: src/async/channels.md:35 +#: src/async/channels.md +msgid "\"ping_handler complete\"" +msgstr "" + +#: src/async/channels.md +msgid "\"Failed to send ping.\"" +msgstr "" + +#: src/async/channels.md +msgid "\"Sent {} pings so far.\"" +msgstr "" + +#: src/async/channels.md +msgid "\"Something went wrong in ping handler task.\"" +msgstr "" + +#: src/async/channels.md msgid "Change the channel size to `3` and see how it affects the execution." msgstr "" -#: src/async/channels.md:37 +#: src/async/channels.md msgid "" "Overall, the interface is similar to the `sync` channels as seen in the " "[morning class](concurrency/channels.md)." msgstr "" -#: src/async/channels.md:40 +#: src/async/channels.md msgid "Try removing the `std::mem::drop` call. What happens? Why?" msgstr "" -#: src/async/channels.md:42 +#: src/async/channels.md msgid "" "The [Flume](https://docs.rs/flume/latest/flume/) crate has channels that " "implement both `sync` and `async` `send` and `recv`. This can be convenient " "for complex applications with both IO and heavy CPU processing tasks." msgstr "" -#: src/async/channels.md:46 +#: src/async/channels.md msgid "" "What makes working with `async` channels preferable is the ability to " "combine them with other `future`s to combine them and create complex control " "flow." msgstr "" -#: src/async/control-flow.md:1 +#: src/async/control-flow.md msgid "Futures Control Flow" msgstr "" -#: src/async/control-flow.md:3 +#: src/async/control-flow.md msgid "" "Futures can be combined together to produce concurrent compute flow graphs. " "We have already seen tasks, that function as independent threads of " "execution." msgstr "" -#: src/async/control-flow.md:6 +#: src/async/control-flow.md msgid "[Join](control-flow/join.md)" msgstr "" -#: src/async/control-flow.md:7 +#: src/async/control-flow.md msgid "[Select](control-flow/select.md)" msgstr "" -#: src/async/control-flow/join.md:3 +#: src/async/control-flow/join.md msgid "" "A join operation waits until all of a set of futures are ready, and returns " "a collection of their results. This is similar to `Promise.all` in " "JavaScript or `asyncio.gather` in Python." msgstr "" -#: src/async/control-flow/join.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"use anyhow::Result;\n" -"use futures::future;\n" -"use reqwest;\n" -"use std::collections::HashMap;\n" -"\n" -"async fn size_of_page(url: &str) -> Result {\n" -" let resp = reqwest::get(url).await?;\n" -" Ok(resp.text().await?.len())\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let urls: [&str; 4] = [\n" -" \"https://google.com\",\n" -" \"https://httpbin.org/ip\",\n" -" \"https://play.rust-lang.org/\",\n" -" \"BAD_URL\",\n" -" ];\n" -" let futures_iter = urls.into_iter().map(size_of_page);\n" -" let results = future::join_all(futures_iter).await;\n" -" let page_sizes_dict: HashMap<&str, Result> =\n" -" urls.into_iter().zip(results.into_iter()).collect();\n" -" println!(\"{:?}\", page_sizes_dict);\n" -"}\n" -"```" +#: src/async/control-flow/join.md +msgid "\"https://google.com\"" msgstr "" -#: src/async/control-flow/join.md:38 +#: src/async/control-flow/join.md +msgid "\"https://httpbin.org/ip\"" +msgstr "" + +#: src/async/control-flow/join.md +msgid "\"https://play.rust-lang.org/\"" +msgstr "" + +#: src/async/control-flow/join.md +msgid "\"BAD_URL\"" +msgstr "" + +#: src/async/control-flow/join.md msgid "" "For multiple futures of disjoint types, you can use `std::future::join!` but " "you must know how many futures you will have at compile time. This is " "currently in the `futures` crate, soon to be stabilised in `std::future`." msgstr "" -#: src/async/control-flow/join.md:42 +#: src/async/control-flow/join.md msgid "" "The risk of `join` is that one of the futures may never resolve, this would " -"cause your program to stall. " +"cause your program to stall." msgstr "" -#: src/async/control-flow/join.md:45 +#: src/async/control-flow/join.md msgid "" "You can also combine `join_all` with `join!` for instance to join all " "requests to an http service as well as a database query. Try adding a " @@ -18669,7 +20744,7 @@ msgid "" "demonstrates `join!`." msgstr "" -#: src/async/control-flow/select.md:3 +#: src/async/control-flow/select.md msgid "" "A select operation waits until any of a set of futures is ready, and " "responds to that future's result. In JavaScript, this is similar to `Promise." @@ -18677,96 +20752,76 @@ msgid "" "FIRST_COMPLETED)`." msgstr "" -#: src/async/control-flow/select.md:8 +#: src/async/control-flow/select.md msgid "" -"This is usually a macro, similar to match, with each arm of the form " -"`pattern = future => statement`. When the future is ready, the statement is " -"executed with the variable bound to the future's result." +"Similar to a match statement, the body of `select!` has a number of arms, " +"each of the form `pattern = future => statement`. When a `future` is ready, " +"its return value is destructured by the `pattern`. The `statement` is then " +"run with the resulting variables. The `statement` result becomes the result " +"of the `select!` macro." msgstr "" -#: src/async/control-flow/select.md:12 -msgid "" -"```rust,editable,compile_fail\n" -"use tokio::sync::mpsc::{self, Receiver};\n" -"use tokio::time::{sleep, Duration};\n" -"\n" -"#[derive(Debug, PartialEq)]\n" -"enum Animal {\n" -" Cat { name: String },\n" -" Dog { name: String },\n" -"}\n" -"\n" -"async fn first_animal_to_finish_race(\n" -" mut cat_rcv: Receiver,\n" -" mut dog_rcv: Receiver,\n" -") -> Option {\n" -" tokio::select! {\n" -" cat_name = cat_rcv.recv() => Some(Animal::Cat { name: cat_name? }),\n" -" dog_name = dog_rcv.recv() => Some(Animal::Dog { name: dog_name? })\n" -" }\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let (cat_sender, cat_receiver) = mpsc::channel(32);\n" -" let (dog_sender, dog_receiver) = mpsc::channel(32);\n" -" tokio::spawn(async move {\n" -" sleep(Duration::from_millis(500)).await;\n" -" cat_sender\n" -" .send(String::from(\"Felix\"))\n" -" .await\n" -" .expect(\"Failed to send cat.\");\n" -" });\n" -" tokio::spawn(async move {\n" -" sleep(Duration::from_millis(50)).await;\n" -" dog_sender\n" -" .send(String::from(\"Rex\"))\n" -" .await\n" -" .expect(\"Failed to send dog.\");\n" -" });\n" -"\n" -" let winner = first_animal_to_finish_race(cat_receiver, dog_receiver)\n" -" .await\n" -" .expect(\"Failed to receive winner\");\n" -"\n" -" println!(\"Winner is {winner:?}\");\n" -"}\n" -"```" +#: src/async/control-flow/select.md +msgid "\"Felix\"" msgstr "" -#: src/async/control-flow/select.md:61 +#: src/async/control-flow/select.md +msgid "\"Failed to send cat.\"" +msgstr "" + +#: src/async/control-flow/select.md +msgid "\"Rex\"" +msgstr "" + +#: src/async/control-flow/select.md +msgid "\"Failed to send dog.\"" +msgstr "" + +#: src/async/control-flow/select.md +msgid "\"Failed to receive winner\"" +msgstr "" + +#: src/async/control-flow/select.md +msgid "\"Winner is {winner:?}\"" +msgstr "" + +#: src/async/control-flow/select.md msgid "" "In this example, we have a race between a cat and a dog. " "`first_animal_to_finish_race` listens to both channels and will pick " "whichever arrives first. Since the dog takes 50ms, it wins against the cat " -"that take 500ms seconds." +"that take 500ms." msgstr "" -#: src/async/control-flow/select.md:66 +#: src/async/control-flow/select.md msgid "" "You can use `oneshot` channels in this example as the channels are supposed " "to receive only one `send`." msgstr "" -#: src/async/control-flow/select.md:69 +#: src/async/control-flow/select.md msgid "" "Try adding a deadline to the race, demonstrating selecting different sorts " "of futures." msgstr "" -#: src/async/control-flow/select.md:72 +#: src/async/control-flow/select.md msgid "" -"Note that `select!` moves the values it is given. It is easiest to use when " -"every execution of `select!` creates new futures. An alternative is to pass " -"`&mut future` instead of the future itself, but this can lead to issues, " -"further discussed in the pinning slide." +"Note that `select!` drops unmatched branches, which cancels their futures. " +"It is easiest to use when every execution of `select!` creates new futures." msgstr "" -#: src/async/pitfalls.md:1 +#: src/async/control-flow/select.md +msgid "" +"An alternative is to pass `&mut future` instead of the future itself, but " +"this can lead to issues, further discussed in the pinning slide." +msgstr "" + +#: src/async/pitfalls.md msgid "Pitfalls of async/await" msgstr "" -#: src/async/pitfalls.md:3 +#: src/async/pitfalls.md msgid "" "Async / await provides convenient and efficient abstraction for concurrent " "asynchronous programming. However, the async/await model in Rust also comes " @@ -18774,23 +20829,27 @@ msgid "" "chapter:" msgstr "" -#: src/async/pitfalls.md:5 +#: src/async/pitfalls.md msgid "[Blocking the Executor](pitfalls/blocking-executor.md)" msgstr "" -#: src/async/pitfalls.md:6 +#: src/async/pitfalls.md msgid "[Pin](pitfalls/pin.md)" msgstr "" -#: src/async/pitfalls.md:7 -msgid "[Async Traits](pitfall/async-traits.md)" +#: src/async/pitfalls.md +msgid "[Async Traits](pitfalls/async-traits.md)" msgstr "" -#: src/async/pitfalls/blocking-executor.md:1 +#: src/async/pitfalls.md +msgid "[Cancellation](pitfalls/cancellation.md)" +msgstr "" + +#: src/async/pitfalls/blocking-executor.md msgid "Blocking the executor" msgstr "" -#: src/async/pitfalls/blocking-executor.md:3 +#: src/async/pitfalls/blocking-executor.md msgid "" "Most async runtimes only allow IO tasks to run concurrently. This means that " "CPU blocking tasks will block the executor and prevent other tasks from " @@ -18798,54 +20857,39 @@ msgid "" "possible." msgstr "" -#: src/async/pitfalls/blocking-executor.md:7 -msgid "" -"```rust,editable,compile_fail\n" -"use futures::future::join_all;\n" -"use std::time::Instant;\n" -"\n" -"async fn sleep_ms(start: &Instant, id: u64, duration_ms: u64) {\n" -" std::thread::sleep(std::time::Duration::from_millis(duration_ms));\n" -" println!(\n" -" \"future {id} slept for {duration_ms}ms, finished after {}ms\",\n" -" start.elapsed().as_millis()\n" -" );\n" -"}\n" -"\n" -"#[tokio::main(flavor = \"current_thread\")]\n" -"async fn main() {\n" -" let start = Instant::now();\n" -" let sleep_futures = (1..=10).map(|t| sleep_ms(&start, t, t * 10));\n" -" join_all(sleep_futures).await;\n" -"}\n" -"```" +#: src/async/pitfalls/blocking-executor.md +msgid "\"future {id} slept for {duration_ms}ms, finished after {}ms\"" msgstr "" -#: src/async/pitfalls/blocking-executor.md:29 +#: src/async/pitfalls/blocking-executor.md +msgid "\"current_thread\"" +msgstr "" + +#: src/async/pitfalls/blocking-executor.md msgid "" "Run the code and see that the sleeps happen consecutively rather than " "concurrently." msgstr "" -#: src/async/pitfalls/blocking-executor.md:32 +#: src/async/pitfalls/blocking-executor.md msgid "" "The `\"current_thread\"` flavor puts all tasks on a single thread. This " "makes the effect more obvious, but the bug is still present in the multi-" "threaded flavor." msgstr "" -#: src/async/pitfalls/blocking-executor.md:36 +#: src/async/pitfalls/blocking-executor.md msgid "" "Switch the `std::thread::sleep` to `tokio::time::sleep` and await its result." msgstr "" -#: src/async/pitfalls/blocking-executor.md:38 +#: src/async/pitfalls/blocking-executor.md msgid "" "Another fix would be to `tokio::task::spawn_blocking` which spawns an actual " "thread and transforms its handle into a future without blocking the executor." msgstr "" -#: src/async/pitfalls/blocking-executor.md:41 +#: src/async/pitfalls/blocking-executor.md msgid "" "You should not think of tasks as OS threads. They do not map 1 to 1 and most " "executors will allow many tasks to run on a single OS thread. This is " @@ -18855,227 +20899,193 @@ msgid "" "situations." msgstr "" -#: src/async/pitfalls/blocking-executor.md:47 +#: src/async/pitfalls/blocking-executor.md msgid "" "Use sync mutexes with care. Holding a mutex over an `.await` may cause " "another task to block, and that task may be running on the same thread." msgstr "" -#: src/async/pitfalls/pin.md:3 +#: src/async/pitfalls/pin.md msgid "" -"When you await a future, all local variables (that would ordinarily be " -"stored on a stack frame) are instead stored in the Future for the current " -"async block. If your future has pointers to data on the stack, those " -"pointers might get invalidated. This is unsafe." +"Async blocks and functions return types implementing the `Future` trait. The " +"type returned is the result of a compiler transformation which turns local " +"variables into data stored inside the future." msgstr "" -#: src/async/pitfalls/pin.md:8 +#: src/async/pitfalls/pin.md msgid "" -"Therefore, you must guarantee that the addresses your future points to don't " -"change. That is why we need to `pin` futures. Using the same future " -"repeatedly in a `select!` often leads to issues with pinned values." +"Some of those variables can hold pointers to other local variables. Because " +"of that, the future should never be moved to a different memory location, as " +"it would invalidate those pointers." msgstr "" -#: src/async/pitfalls/pin.md:12 +#: src/async/pitfalls/pin.md +msgid "" +"To prevent moving the future type in memory, it can only be polled through a " +"pinned pointer. `Pin` is a wrapper around a reference that disallows all " +"operations that would move the instance it points to into a different memory " +"location." +msgstr "" + +#: src/async/pitfalls/pin.md msgid "" -"```rust,editable,compile_fail\n" -"use tokio::sync::{mpsc, oneshot};\n" -"use tokio::task::spawn;\n" -"use tokio::time::{sleep, Duration};\n" -"\n" "// A work item. In this case, just sleep for the given time and respond\n" "// with a message on the `respond_on` channel.\n" -"#[derive(Debug)]\n" -"struct Work {\n" -" input: u32,\n" -" respond_on: oneshot::Sender,\n" -"}\n" -"\n" -"// A worker which listens for work on a queue and performs it.\n" -"async fn worker(mut work_queue: mpsc::Receiver) {\n" -" let mut iterations = 0;\n" -" loop {\n" -" tokio::select! {\n" -" Some(work) = work_queue.recv() => {\n" -" sleep(Duration::from_millis(10)).await; // Pretend to work.\n" -" work.respond_on\n" -" .send(work.input * 1000)\n" -" .expect(\"failed to send response\");\n" -" iterations += 1;\n" -" }\n" -" // TODO: report number of iterations every 100ms\n" -" }\n" -" }\n" -"}\n" -"\n" -"// A requester which requests work and waits for it to complete.\n" -"async fn do_work(work_queue: &mpsc::Sender, input: u32) -> u32 {\n" -" let (tx, rx) = oneshot::channel();\n" -" work_queue\n" -" .send(Work {\n" -" input,\n" -" respond_on: tx,\n" -" })\n" -" .await\n" -" .expect(\"failed to send on work queue\");\n" -" rx.await.expect(\"failed waiting for response\")\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let (tx, rx) = mpsc::channel(10);\n" -" spawn(worker(rx));\n" -" for i in 0..100 {\n" -" let resp = do_work(&tx, i).await;\n" -" println!(\"work result for iteration {i}: {resp}\");\n" -" }\n" -"}\n" -"```" msgstr "" -#: src/async/pitfalls/pin.md:68 +#: src/async/pitfalls/pin.md +msgid "// A worker which listens for work on a queue and performs it.\n" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "// Pretend to work.\n" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "\"failed to send response\"" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "// TODO: report number of iterations every 100ms\n" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "// A requester which requests work and waits for it to complete.\n" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "\"failed to send on work queue\"" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "\"failed waiting for response\"" +msgstr "" + +#: src/async/pitfalls/pin.md +msgid "\"work result for iteration {i}: {resp}\"" +msgstr "" + +#: src/async/pitfalls/pin.md msgid "" "You may recognize this as an example of the actor pattern. Actors typically " "call `select!` in a loop." msgstr "" -#: src/async/pitfalls/pin.md:71 +#: src/async/pitfalls/pin.md msgid "" "This serves as a summation of a few of the previous lessons, so take your " "time with it." msgstr "" -#: src/async/pitfalls/pin.md:74 +#: src/async/pitfalls/pin.md msgid "" "Naively add a `_ = sleep(Duration::from_millis(100)) => { println!(..) }` to " "the `select!`. This will never execute. Why?" msgstr "" -#: src/async/pitfalls/pin.md:77 +#: src/async/pitfalls/pin.md msgid "" "Instead, add a `timeout_fut` containing that future outside of the `loop`:" msgstr "" -#: src/async/pitfalls/pin.md:79 -msgid "" -"```rust,compile_fail\n" -"let mut timeout_fut = sleep(Duration::from_millis(100));\n" -"loop {\n" -" select! {\n" -" ..,\n" -" _ = timeout_fut => { println!(..); },\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/async/pitfalls/pin.md:88 +#: src/async/pitfalls/pin.md msgid "" "This still doesn't work. Follow the compiler errors, adding `&mut` to the " "`timeout_fut` in the `select!` to work around the move, then using `Box::" "pin`:" msgstr "" -#: src/async/pitfalls/pin.md:92 -msgid "" -"```rust,compile_fail\n" -"let mut timeout_fut = Box::pin(sleep(Duration::from_millis(100)));\n" -"loop {\n" -" select! {\n" -" ..,\n" -" _ = &mut timeout_fut => { println!(..); },\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/async/pitfalls/pin.md:102 +#: src/async/pitfalls/pin.md msgid "" "This compiles, but once the timeout expires it is `Poll::Ready` on every " "iteration (a fused future would help with this). Update to reset " "`timeout_fut` every time it expires." msgstr "" -#: src/async/pitfalls/pin.md:106 +#: src/async/pitfalls/pin.md msgid "" "Box allocates on the heap. In some cases, `std::pin::pin!` (only recently " "stabilized, with older code often using `tokio::pin!`) is also an option, " "but that is difficult to use for a future that is reassigned." msgstr "" -#: src/async/pitfalls/pin.md:110 +#: src/async/pitfalls/pin.md msgid "" "Another alternative is to not use `pin` at all but spawn another task that " "will send to a `oneshot` channel every 100ms." msgstr "" -#: src/async/pitfalls/async-traits.md:3 +#: src/async/pitfalls/pin.md msgid "" -"Async methods in traits are not yet supported in the stable channel ([An " -"experimental feature exists in nightly and should be stabilized in the mid " -"term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-" -"nightly.html))" +"Data that contains pointers to itself is called self-referential. Normally, " +"the Rust borrow checker would prevent self-referential data from being " +"moved, as the references cannot outlive the data they point to. However, the " +"code transformation for async blocks and functions is not verified by the " +"borrow checker." msgstr "" -#: src/async/pitfalls/async-traits.md:5 +#: src/async/pitfalls/pin.md msgid "" -"The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) " -"provides a workaround through a macro:" +"`Pin` is a wrapper around a reference. An object cannot be moved from its " +"place using a pinned pointer. However, it can still be moved through an " +"unpinned pointer." msgstr "" -#: src/async/pitfalls/async-traits.md:7 +#: src/async/pitfalls/pin.md msgid "" -"```rust,editable,compile_fail\n" -"use async_trait::async_trait;\n" -"use std::time::Instant;\n" -"use tokio::time::{sleep, Duration};\n" -"\n" -"#[async_trait]\n" -"trait Sleeper {\n" -" async fn sleep(&self);\n" -"}\n" -"\n" -"struct FixedSleeper {\n" -" sleep_ms: u64,\n" -"}\n" -"\n" -"#[async_trait]\n" -"impl Sleeper for FixedSleeper {\n" -" async fn sleep(&self) {\n" -" sleep(Duration::from_millis(self.sleep_ms)).await;\n" -" }\n" -"}\n" -"\n" -"async fn run_all_sleepers_multiple_times(sleepers: Vec>, " -"n_times: usize) {\n" -" for _ in 0..n_times {\n" -" println!(\"running all sleepers..\");\n" -" for sleeper in &sleepers {\n" -" let start = Instant::now();\n" -" sleeper.sleep().await;\n" -" println!(\"slept for {}ms\", start.elapsed().as_millis());\n" -" }\n" -" }\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" let sleepers: Vec> = vec![\n" -" Box::new(FixedSleeper { sleep_ms: 50 }),\n" -" Box::new(FixedSleeper { sleep_ms: 100 }),\n" -" ];\n" -" run_all_sleepers_multiple_times(sleepers, 5).await;\n" -"}\n" -"```" +"The `poll` method of the `Future` trait uses `Pin<&mut Self>` instead of " +"`&mut Self` to refer to the instance. That's why it can only be called on a " +"pinned pointer." msgstr "" -#: src/async/pitfalls/async-traits.md:51 +#: src/async/pitfalls/async-traits.md +msgid "" +"Async methods in traits are were stabilized only recently, in the 1.75 " +"release. This required support for using return-position `impl Trait` (RPIT) " +"in traits, as the desugaring for `async fn` includes `-> impl Future`." +msgstr "" + +#: src/async/pitfalls/async-traits.md +msgid "" +"However, even with the native support today there are some pitfalls around " +"`async fn` and RPIT in traits:" +msgstr "" + +#: src/async/pitfalls/async-traits.md +msgid "" +"Return-position impl Trait captures all in-scope lifetimes (so some patterns " +"of borrowing cannot be expressed)" +msgstr "" + +#: src/async/pitfalls/async-traits.md +msgid "" +"Traits whose methods use return-position `impl trait` or `async` are not " +"`dyn` compatible." +msgstr "" + +#: src/async/pitfalls/async-traits.md +msgid "" +"If we do need `dyn` support, the crate [async_trait](https://docs.rs/async-" +"trait/latest/async_trait/) provides a workaround through a macro, with some " +"caveats:" +msgstr "" + +#: src/async/pitfalls/async-traits.md +msgid "\"running all sleepers..\"" +msgstr "" + +#: src/async/pitfalls/async-traits.md +msgid "\"slept for {}ms\"" +msgstr "" + +#: src/async/pitfalls/async-traits.md msgid "" "`async_trait` is easy to use, but note that it's using heap allocations to " "achieve this. This heap allocation has performance overhead." msgstr "" -#: src/async/pitfalls/async-traits.md:54 +#: src/async/pitfalls/async-traits.md msgid "" "The challenges in language support for `async trait` are deep Rust and " "probably not worth describing in-depth. Niko Matsakis did a good job of " @@ -19084,102 +21094,139 @@ msgid "" "digging deeper." msgstr "" -#: src/async/pitfalls/async-traits.md:60 +#: src/async/pitfalls/async-traits.md msgid "" "Try creating a new sleeper struct that will sleep for a random amount of " "time and adding it to the Vec." msgstr "" -#: src/exercises/concurrency/afternoon.md:3 +#: src/async/pitfalls/cancellation.md +msgid "" +"Dropping a future implies it can never be polled again. This is called " +"_cancellation_ and it can occur at any `await` point. Care is needed to " +"ensure the system works correctly even when futures are cancelled. For " +"example, it shouldn't deadlock or lose data." +msgstr "" + +#: src/async/pitfalls/cancellation.md +#, fuzzy +msgid "\"not UTF-8\"" +msgstr "UTF-8" + +#: src/async/pitfalls/cancellation.md +msgid "\"hi\\nthere\\n\"" +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "\"tick!\"" +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"The compiler doesn't help with cancellation-safety. You need to read API " +"documentation and consider what state your `async fn` holds." +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"Unlike `panic` and `?`, cancellation is part of normal control flow (vs " +"error-handling)." +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "The example loses parts of the string." +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"Whenever the `tick()` branch finishes first, `next()` and its `buf` are " +"dropped." +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"`LinesReader` can be made cancellation-safe by making `buf` part of the " +"struct:" +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "// prefix buf and bytes with self.\n" +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"[`Interval::tick`](https://docs.rs/tokio/latest/tokio/time/struct.Interval." +"html#method.tick) is cancellation-safe because it keeps track of whether a " +"tick has been 'delivered'." +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"[`AsyncReadExt::read`](https://docs.rs/tokio/latest/tokio/io/trait." +"AsyncReadExt.html#method.read) is cancellation-safe because it either " +"returns or doesn't read data." +msgstr "" + +#: src/async/pitfalls/cancellation.md +msgid "" +"[`AsyncBufReadExt::read_line`](https://docs.rs/tokio/latest/tokio/io/trait." +"AsyncBufReadExt.html#method.read_line) is similar to the example and _isn't_ " +"cancellation-safe. See its documentation for details and alternatives." +msgstr "" + +#: src/exercises/concurrency/afternoon.md msgid "" "To practice your Async Rust skills, we have again two exercises for you:" msgstr "" -#: src/exercises/concurrency/afternoon.md:5 +#: src/exercises/concurrency/afternoon.md msgid "" "Dining philosophers: we already saw this problem in the morning. This time " "you are going to implement it with Async Rust." msgstr "" -#: src/exercises/concurrency/afternoon.md:8 +#: src/exercises/concurrency/afternoon.md msgid "" "A Broadcast Chat Application: this is a larger project that allows you " "experiment with more advanced Async Rust features." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:1 -#: src/exercises/concurrency/solutions-afternoon.md:3 -msgid "Dining Philosophers - Async" -msgstr "" +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +#, fuzzy +msgid "Dining Philosophers --- Async" +msgstr "哲學家就餐問題" -#: src/exercises/concurrency/dining-philosophers-async.md:3 +#: src/exercises/concurrency/dining-philosophers-async.md msgid "" "See [dining philosophers](dining-philosophers.md) for a description of the " "problem." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:6 +#: src/exercises/concurrency/dining-philosophers-async.md msgid "" "As before, you will need a local [Cargo installation](../../cargo/running-" "locally.md) for this exercise. Copy the code below to a file called `src/" "main.rs`, fill out the blanks, and test that `cargo run` does not deadlock:" msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:13 -msgid "" -"```rust,compile_fail\n" -"use std::sync::Arc;\n" -"use tokio::time;\n" -"use tokio::sync::mpsc::{self, Sender};\n" -"use tokio::sync::Mutex;\n" -"\n" -"struct Fork;\n" -"\n" -"struct Philosopher {\n" -" name: String,\n" -" // left_fork: ...\n" -" // right_fork: ...\n" -" // thoughts: ...\n" -"}\n" -"\n" -"impl Philosopher {\n" -" async fn think(&self) {\n" -" self.thoughts\n" -" .send(format!(\"Eureka! {} has a new idea!\", &self.name))." -"await\n" -" .unwrap();\n" -" }\n" -"\n" -" async fn eat(&self) {\n" -" // Pick up forks...\n" -" println!(\"{} is eating...\", &self.name);\n" -" time::sleep(time::Duration::from_millis(5)).await;\n" -" }\n" -"}\n" -"\n" -"static PHILOSOPHERS: &[&str] =\n" -" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" // Create forks\n" -"\n" -" // Create philosophers\n" -"\n" -" // Make them think and eat\n" -"\n" -" // Output their thoughts\n" -"}\n" -"```" +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Keep trying until we have both forks\n" msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:57 +#: src/exercises/concurrency/dining-philosophers-async.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Make them think and eat\n" +msgstr "" + +#: src/exercises/concurrency/dining-philosophers-async.md msgid "" "Since this time you are using Async Rust, you'll need a `tokio` dependency. " "You can use the following `Cargo.toml`:" msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:62 +#: src/exercises/concurrency/dining-philosophers-async.md msgid "" "```toml\n" "[package]\n" @@ -19188,22 +21235,22 @@ msgid "" "edition = \"2021\"\n" "\n" "[dependencies]\n" -"tokio = {version = \"1.26.0\", features = [\"sync\", \"time\", \"macros\", " -"\"rt-multi-thread\"]}\n" +"tokio = { version = \"1.26.0\", features = [\"sync\", \"time\", \"macros\", " +"\"rt-multi-thread\"] }\n" "```" msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:72 +#: src/exercises/concurrency/dining-philosophers-async.md msgid "" "Also note that this time you have to use the `Mutex` and the `mpsc` module " "from the `tokio` crate." msgstr "" -#: src/exercises/concurrency/dining-philosophers-async.md:77 -msgid "Can you make your implementation single-threaded? " +#: src/exercises/concurrency/dining-philosophers-async.md +msgid "Can you make your implementation single-threaded?" msgstr "" -#: src/exercises/concurrency/chat-app.md:3 +#: src/exercises/concurrency/chat-app.md msgid "" "In this exercise, we want to use our new knowledge to implement a broadcast " "chat application. We have a chat server that the clients connect to and " @@ -19212,23 +21259,23 @@ msgid "" "that it receives to all the clients." msgstr "" -#: src/exercises/concurrency/chat-app.md:9 +#: src/exercises/concurrency/chat-app.md msgid "" "For this, we use [a broadcast channel](https://docs.rs/tokio/latest/tokio/" "sync/broadcast/fn.channel.html) on the server, and [`tokio_websockets`]" -"(https://docs.rs/tokio-websockets/0.3.2/tokio_websockets/) for the " -"communication between the client and the server." +"(https://docs.rs/tokio-websockets/) for the communication between the client " +"and the server." msgstr "" -#: src/exercises/concurrency/chat-app.md:13 +#: src/exercises/concurrency/chat-app.md msgid "Create a new Cargo project and add the following dependencies:" msgstr "" -#: src/exercises/concurrency/chat-app.md:15 -msgid "`Cargo.toml`:" +#: src/exercises/concurrency/chat-app.md +msgid "_Cargo.toml_:" msgstr "" -#: src/exercises/concurrency/chat-app.md:19 +#: src/exercises/concurrency/chat-app.md msgid "" "```toml\n" "[package]\n" @@ -19237,57 +21284,57 @@ msgid "" "edition = \"2021\"\n" "\n" "[dependencies]\n" -"futures-util = \"0.3.28\"\n" -"http = \"0.2.9\"\n" -"tokio = { version = \"1.28.1\", features = [\"full\"] }\n" -"tokio-websockets = \"0.3.2\"\n" +"futures-util = { version = \"0.3.30\", features = [\"sink\"] }\n" +"http = \"1.0.0\"\n" +"tokio = { version = \"1.36.0\", features = [\"full\"] }\n" +"tokio-websockets = { version = \"0.7.0\", features = [\"client\", " +"\"fastrand\", \"server\", \"sha1_smol\"] }\n" "```" msgstr "" -#: src/exercises/concurrency/chat-app.md:32 +#: src/exercises/concurrency/chat-app.md msgid "The required APIs" msgstr "" -#: src/exercises/concurrency/chat-app.md:33 +#: src/exercises/concurrency/chat-app.md msgid "" "You are going to need the following functions from `tokio` and " -"[`tokio_websockets`](https://docs.rs/tokio-websockets/0.3.2/" -"tokio_websockets/). Spend a few minutes to familiarize yourself with the " -"API. " +"[`tokio_websockets`](https://docs.rs/tokio-websockets/). Spend a few minutes " +"to familiarize yourself with the API." msgstr "" -#: src/exercises/concurrency/chat-app.md:37 +#: src/exercises/concurrency/chat-app.md msgid "" -"[WebsocketStream::next()](https://docs.rs/tokio-websockets/0.3.2/" -"tokio_websockets/proto/struct.WebsocketStream.html#method.next): for " +"[StreamExt::next()](https://docs.rs/futures-util/0.3.28/futures_util/stream/" +"trait.StreamExt.html#method.next) implemented by `WebSocketStream`: for " "asynchronously reading messages from a Websocket Stream." msgstr "" -#: src/exercises/concurrency/chat-app.md:39 +#: src/exercises/concurrency/chat-app.md msgid "" "[SinkExt::send()](https://docs.rs/futures-util/0.3.28/futures_util/sink/" -"trait.SinkExt.html#method.send) implemented by `WebsocketStream`: for " +"trait.SinkExt.html#method.send) implemented by `WebSocketStream`: for " "asynchronously sending messages on a Websocket Stream." msgstr "" -#: src/exercises/concurrency/chat-app.md:41 +#: src/exercises/concurrency/chat-app.md msgid "" -"[BufReader::read_line()](https://docs.rs/tokio/latest/tokio/io/struct.Lines." +"[Lines::next_line()](https://docs.rs/tokio/latest/tokio/io/struct.Lines." "html#method.next_line): for asynchronously reading user messages from the " "standard input." msgstr "" -#: src/exercises/concurrency/chat-app.md:43 +#: src/exercises/concurrency/chat-app.md msgid "" "[Sender::subscribe()](https://docs.rs/tokio/latest/tokio/sync/broadcast/" "struct.Sender.html#method.subscribe): for subscribing to a broadcast channel." msgstr "" -#: src/exercises/concurrency/chat-app.md:46 +#: src/exercises/concurrency/chat-app.md msgid "Two binaries" msgstr "" -#: src/exercises/concurrency/chat-app.md:48 +#: src/exercises/concurrency/chat-app.md msgid "" "Normally in a Cargo project, you can have only one binary, and one `src/main." "rs` file. In this project, we need two binaries. One for the client, and one " @@ -19295,135 +21342,83 @@ msgid "" "but we are going to put them in a single Cargo project with two binaries. " "For this to work, the client and the server code should go under `src/bin` " "(see the [documentation](https://doc.rust-lang.org/cargo/reference/cargo-" -"targets.html#binaries)). " +"targets.html#binaries))." msgstr "" -#: src/exercises/concurrency/chat-app.md:55 +#: src/exercises/concurrency/chat-app.md msgid "" "Copy the following server and client code into `src/bin/server.rs` and `src/" "bin/client.rs`, respectively. Your task is to complete these files as " -"described below. " +"described below." msgstr "" -#: src/exercises/concurrency/chat-app.md:59 -#: src/exercises/concurrency/solutions-afternoon.md:117 -msgid "`src/bin/server.rs`:" +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "_src/bin/server.rs_:" msgstr "" -#: src/exercises/concurrency/chat-app.md:63 -msgid "" -"```rust,compile_fail\n" -"use futures_util::sink::SinkExt;\n" -"use std::error::Error;\n" -"use std::net::SocketAddr;\n" -"use tokio::net::{TcpListener, TcpStream};\n" -"use tokio::sync::broadcast::{channel, Sender};\n" -"use tokio_websockets::{Message, ServerBuilder, WebsocketStream};\n" -"\n" -"async fn handle_connection(\n" -" addr: SocketAddr,\n" -" mut ws_stream: WebsocketStream,\n" -" bcast_tx: Sender,\n" -") -> Result<(), Box> {\n" -"\n" -" // TODO: For a hint, see the description of the task below.\n" -"\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> Result<(), Box> {\n" -" let (bcast_tx, _) = channel(16);\n" -"\n" -" let listener = TcpListener::bind(\"127.0.0.1:2000\").await?;\n" -" println!(\"listening on port 2000\");\n" -"\n" -" loop {\n" -" let (socket, addr) = listener.accept().await?;\n" -" println!(\"New connection from {addr:?}\");\n" -" let bcast_tx = bcast_tx.clone();\n" -" tokio::spawn(async move {\n" -" // Wrap the raw TCP stream into a websocket.\n" -" let ws_stream = ServerBuilder::new().accept(socket).await?;\n" -"\n" -" handle_connection(addr, ws_stream, bcast_tx).await\n" -" });\n" -" }\n" -"}\n" -"```" +#: src/exercises/concurrency/chat-app.md +msgid "// TODO: For a hint, see the description of the task below.\n" msgstr "" -#: src/exercises/concurrency/chat-app.md:102 -#: src/exercises/concurrency/solutions-afternoon.md:202 -msgid "`src/bin/client.rs`:" +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"127.0.0.1:2000\"" msgstr "" -#: src/exercises/concurrency/chat-app.md:106 -msgid "" -"```rust,compile_fail\n" -"use futures_util::SinkExt;\n" -"use http::Uri;\n" -"use tokio::io::{AsyncBufReadExt, BufReader};\n" -"use tokio_websockets::{ClientBuilder, Message};\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> Result<(), tokio_websockets::Error> {\n" -" let mut ws_stream = ClientBuilder::from_uri(Uri::" -"from_static(\"ws://127.0.0.1:2000\"))\n" -" .connect()\n" -" .await?;\n" -"\n" -" let stdin = tokio::io::stdin();\n" -" let mut stdin = BufReader::new(stdin);\n" -"\n" -"\n" -" // TODO: For a hint, see the description of the task below.\n" -"\n" -"}\n" -"```" +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"listening on port 2000\"" msgstr "" -#: src/exercises/concurrency/chat-app.md:127 +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"New connection from {addr:?}\"" +msgstr "" + +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Wrap the raw TCP stream into a websocket.\n" +msgstr "" + +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "_src/bin/client.rs_:" +msgstr "" + +#: src/exercises/concurrency/chat-app.md +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"ws://127.0.0.1:2000\"" +msgstr "" + +#: src/exercises/concurrency/chat-app.md msgid "Running the binaries" msgstr "" -#: src/exercises/concurrency/chat-app.md:128 +#: src/exercises/concurrency/chat-app.md msgid "Run the server with:" msgstr "" -#: src/exercises/concurrency/chat-app.md:130 -msgid "" -"```shell\n" -"$ cargo run --bin server\n" -"```" -msgstr "" - -#: src/exercises/concurrency/chat-app.md:134 +#: src/exercises/concurrency/chat-app.md msgid "and the client with:" msgstr "" -#: src/exercises/concurrency/chat-app.md:136 -msgid "" -"```shell\n" -"$ cargo run --bin client\n" -"```" -msgstr "" - -#: src/exercises/concurrency/chat-app.md:142 +#: src/exercises/concurrency/chat-app.md msgid "Implement the `handle_connection` function in `src/bin/server.rs`." msgstr "" -#: src/exercises/concurrency/chat-app.md:143 +#: src/exercises/concurrency/chat-app.md msgid "" "Hint: Use `tokio::select!` for concurrently performing two tasks in a " "continuous loop. One task receives messages from the client and broadcasts " "them. The other sends messages received by the server to the client." msgstr "" -#: src/exercises/concurrency/chat-app.md:146 +#: src/exercises/concurrency/chat-app.md msgid "Complete the main function in `src/bin/client.rs`." msgstr "" -#: src/exercises/concurrency/chat-app.md:147 +#: src/exercises/concurrency/chat-app.md msgid "" "Hint: As before, use `tokio::select!` in a continuous loop for concurrently " "performing two tasks: (1) reading user messages from standard input and " @@ -19431,20 +21426,79 @@ msgid "" "displaying them for the user." msgstr "" -#: src/exercises/concurrency/chat-app.md:151 +#: src/exercises/concurrency/chat-app.md msgid "" "Optional: Once you are done, change the code to broadcast messages to all " "clients, but the sender of the message." msgstr "" -#: src/thanks.md:3 +#: src/exercises/concurrency/solutions-afternoon.md +msgid "Concurrency Afternoon Exercise" +msgstr "並行:下午練習" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "([back to exercise](dining-philosophers-async.md))" +msgstr "([返回練習](dining-philosophers-async.md))" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "" +"// If we didn't get the left fork, drop the right fork if we\n" +" // have it and let other tasks make progress.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "" +"// If we didn't get the right fork, drop the left fork and let\n" +" // other tasks make progress.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// The locks are dropped here\n" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// tx is dropped here, so we don't need to explicitly drop it later\n" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Here is a thought: {thought}\"" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "([back to exercise](chat-app.md))" +msgstr "([返回練習](chat-app.md))" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"Welcome to chat! Type a message\"" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "" +"// A continuous loop for concurrently performing two tasks: (1) receiving\n" +" // messages from `ws_stream` and broadcasting them, and (2) receiving\n" +" // messages on `bcast_rx` and sending them to the client.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"From client {addr:?} {text:?}\"" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "// Continuous loop for concurrently sending and receiving messages.\n" +msgstr "" + +#: src/exercises/concurrency/solutions-afternoon.md +msgid "\"From server: {}\"" +msgstr "" + +#: src/thanks.md msgid "" "_Thank you for taking Comprehensive Rust 🦀!_ We hope you enjoyed it and " "that it was useful." msgstr "" "感謝您參加 Comprehensive Rust 🦀 課程!__希望您喜歡這門課,並能學以致用。" -#: src/thanks.md:6 +#: src/thanks.md msgid "" "We've had a lot of fun putting the course together. The course is not " "perfect, so if you spotted any mistakes or have ideas for improvements, " @@ -19455,25 +21509,482 @@ msgstr "" "有改善的想法,歡迎[透過 GitHub 與我們聯絡](https://github.com/google/" "comprehensive-rust/discussions)。我們很樂於傾聽您的意見!" -#: src/other-resources.md:1 +#: src/glossary.md +msgid "" +"The following is a glossary which aims to give a short definition of many " +"Rust terms. For translations, this also serves to connect the term back to " +"the English original." +msgstr "" + +#: src/glossary.md +msgid "" +"allocate: \n" +"Dynamic memory allocation on [the heap](memory-management/stack-vs-heap.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"argument: \n" +"Information that is passed into a function or method." +msgstr "" + +#: src/glossary.md +msgid "" +"Bare-metal Rust: \n" +"Low-level Rust development, often deployed to a system without an operating " +"system. See [Bare-metal Rust](bare-metal.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"block: \n" +"See [Blocks](control-flow/blocks.md) and _scope_." +msgstr "" + +#: src/glossary.md +msgid "" +"borrow: \n" +"See [Borrowing](ownership/borrowing.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"borrow checker: \n" +"The part of the Rust compiler which checks that all borrows are valid." +msgstr "" + +#: src/glossary.md +msgid "" +"brace: \n" +"`{` and `}`. Also called _curly brace_, they delimit _blocks_." +msgstr "" + +#: src/glossary.md +msgid "" +"build: \n" +"The process of converting source code into executable code or a usable " +"program." +msgstr "" + +#: src/glossary.md +msgid "" +"call: \n" +"To invoke or execute a function or method." +msgstr "" + +#: src/glossary.md +msgid "" +"channel: \n" +"Used to safely pass messages [between threads](concurrency/channels.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"Comprehensive Rust 🦀: \n" +"The courses here are jointly called Comprehensive Rust 🦀." +msgstr "" + +#: src/glossary.md +msgid "" +"concurrency: \n" +"The execution of multiple tasks or processes at the same time." +msgstr "" + +#: src/glossary.md +msgid "" +"Concurrency in Rust: \n" +"See [Concurrency in Rust](concurrency.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"constant: \n" +"A value that does not change during the execution of a program." +msgstr "" + +#: src/glossary.md +msgid "" +"control flow: \n" +"The order in which the individual statements or instructions are executed in " +"a program." +msgstr "" + +#: src/glossary.md +msgid "" +"crash: \n" +"An unexpected and unhandled failure or termination of a program." +msgstr "" + +#: src/glossary.md +msgid "" +"enumeration: \n" +"A data type that holds one of several named constants, possibly with an " +"associated tuple or struct." +msgstr "" + +#: src/glossary.md +msgid "" +"error: \n" +"An unexpected condition or result that deviates from the expected behavior." +msgstr "" + +#: src/glossary.md +msgid "" +"error handling: \n" +"The process of managing and responding to errors that occur during program " +"execution." +msgstr "" + +#: src/glossary.md +msgid "" +"exercise: \n" +"A task or problem designed to practice and test programming skills." +msgstr "" + +#: src/glossary.md +msgid "" +"function: \n" +"A reusable block of code that performs a specific task." +msgstr "" + +#: src/glossary.md +msgid "" +"garbage collector: \n" +"A mechanism that automatically frees up memory occupied by objects that are " +"no longer in use." +msgstr "" + +#: src/glossary.md +msgid "" +"generics: \n" +"A feature that allows writing code with placeholders for types, enabling " +"code reuse with different data types." +msgstr "" + +#: src/glossary.md +msgid "" +"immutable: \n" +"Unable to be changed after creation." +msgstr "" + +#: src/glossary.md +msgid "" +"integration test: \n" +"A type of test that verifies the interactions between different parts or " +"components of a system." +msgstr "" + +#: src/glossary.md +msgid "" +"keyword: \n" +"A reserved word in a programming language that has a specific meaning and " +"cannot be used as an identifier." +msgstr "" + +#: src/glossary.md +msgid "" +"library: \n" +"A collection of precompiled routines or code that can be used by programs." +msgstr "" + +#: src/glossary.md +msgid "" +"macro: \n" +"Rust macros can be recognized by a `!` in the name. Macros are used when " +"normal functions are not enough. A typical example is `format!`, which takes " +"a variable number of arguments, which isn't supported by Rust functions." +msgstr "" + +#: src/glossary.md +msgid "" +"`main` function: \n" +"Rust programs start executing with the `main` function." +msgstr "" + +#: src/glossary.md +msgid "" +"match: \n" +"A control flow construct in Rust that allows for pattern matching on the " +"value of an expression." +msgstr "" + +#: src/glossary.md +msgid "" +"memory leak: \n" +"A situation where a program fails to release memory that is no longer " +"needed, leading to a gradual increase in memory usage." +msgstr "" + +#: src/glossary.md +msgid "" +"method: \n" +"A function associated with an object or a type in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"module: \n" +"A namespace that contains definitions, such as functions, types, or traits, " +"to organize code in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"move: \n" +"The transfer of ownership of a value from one variable to another in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"mutable: \n" +"A property in Rust that allows variables to be modified after they have been " +"declared." +msgstr "" + +#: src/glossary.md +msgid "" +"ownership: \n" +"The concept in Rust that defines which part of the code is responsible for " +"managing the memory associated with a value." +msgstr "" + +#: src/glossary.md +msgid "" +"panic: \n" +"An unrecoverable error condition in Rust that results in the termination of " +"the program." +msgstr "" + +#: src/glossary.md +msgid "" +"parameter: \n" +"A value that is passed into a function or method when it is called." +msgstr "" + +#: src/glossary.md +msgid "" +"pattern: \n" +"A combination of values, literals, or structures that can be matched against " +"an expression in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"payload: \n" +"The data or information carried by a message, event, or data structure." +msgstr "" + +#: src/glossary.md +msgid "" +"program: \n" +"A set of instructions that a computer can execute to perform a specific task " +"or solve a particular problem." +msgstr "" + +#: src/glossary.md +msgid "" +"programming language: \n" +"A formal system used to communicate instructions to a computer, such as Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"receiver: \n" +"The first parameter in a Rust method that represents the instance on which " +"the method is called." +msgstr "" + +#: src/glossary.md +msgid "" +"reference counting: \n" +"A memory management technique in which the number of references to an object " +"is tracked, and the object is deallocated when the count reaches zero." +msgstr "" + +#: src/glossary.md +msgid "" +"return: \n" +"A keyword in Rust used to indicate the value to be returned from a function." +msgstr "" + +#: src/glossary.md +msgid "" +"Rust: \n" +"A systems programming language that focuses on safety, performance, and " +"concurrency." +msgstr "" + +#: src/glossary.md +msgid "" +"Rust Fundamentals: \n" +"Days 1 to 4 of this course." +msgstr "" + +#: src/glossary.md +msgid "" +"Rust in Android: \n" +"See [Rust in Android](android.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"Rust in Chromium: \n" +"See [Rust in Chromium](chromium.md)." +msgstr "" + +#: src/glossary.md +msgid "" +"safe: \n" +"Refers to code that adheres to Rust's ownership and borrowing rules, " +"preventing memory-related errors." +msgstr "" + +#: src/glossary.md +msgid "" +"scope: \n" +"The region of a program where a variable is valid and can be used." +msgstr "" + +#: src/glossary.md +msgid "" +"standard library: \n" +"A collection of modules providing essential functionality in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"static: \n" +"A keyword in Rust used to define static variables or items with a `'static` " +"lifetime." +msgstr "" + +#: src/glossary.md +msgid "" +"string: \n" +"A data type storing textual data. See [`String` vs `str`](basic-syntax/" +"string-slices.html) for more." +msgstr "" + +#: src/glossary.md +msgid "" +"struct: \n" +"A composite data type in Rust that groups together variables of different " +"types under a single name." +msgstr "" + +#: src/glossary.md +msgid "" +"test: \n" +"A Rust module containing functions that test the correctness of other " +"functions." +msgstr "" + +#: src/glossary.md +msgid "" +"thread: \n" +"A separate sequence of execution in a program, allowing concurrent execution." +msgstr "" + +#: src/glossary.md +msgid "" +"thread safety: \n" +"The property of a program that ensures correct behavior in a multithreaded " +"environment." +msgstr "" + +#: src/glossary.md +msgid "" +"trait: \n" +"A collection of methods defined for an unknown type, providing a way to " +"achieve polymorphism in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"trait bound: \n" +"An abstraction where you can require types to implement some traits of your " +"interest." +msgstr "" + +#: src/glossary.md +msgid "" +"tuple: \n" +"A composite data type that contains variables of different types. Tuple " +"fields have no names, and are accessed by their ordinal numbers." +msgstr "" + +#: src/glossary.md +msgid "" +"type: \n" +"A classification that specifies which operations can be performed on values " +"of a particular kind in Rust." +msgstr "" + +#: src/glossary.md +msgid "" +"type inference: \n" +"The ability of the Rust compiler to deduce the type of a variable or " +"expression." +msgstr "" + +#: src/glossary.md +msgid "" +"undefined behavior: \n" +"Actions or conditions in Rust that have no specified result, often leading " +"to unpredictable program behavior." +msgstr "" + +#: src/glossary.md +msgid "" +"union: \n" +"A data type that can hold values of different types but only one at a time." +msgstr "" + +#: src/glossary.md +msgid "" +"unit test: \n" +"Rust comes with built-in support for running small unit tests and larger " +"integration tests. See [Unit Tests](testing/unit-tests.html)." +msgstr "" + +#: src/glossary.md +msgid "" +"unit type: \n" +"Type that holds no data, written as a tuple with no members." +msgstr "" + +#: src/glossary.md +msgid "" +"unsafe: \n" +"The subset of Rust which allows you to trigger _undefined behavior_. See " +"[Unsafe Rust](unsafe.html)." +msgstr "" + +#: src/glossary.md +msgid "" +"variable: \n" +"A memory location storing data. Variables are valid in a _scope_." +msgstr "" + +#: src/other-resources.md msgid "Other Rust Resources" msgstr "其他 Rust 資源" -#: src/other-resources.md:3 +#: src/other-resources.md msgid "" "The Rust community has created a wealth of high-quality and free resources " "online." msgstr "Rust 社群在線上提供了大量優質的免費資源。" -#: src/other-resources.md:6 +#: src/other-resources.md msgid "Official Documentation" msgstr "官方說明文件" -#: src/other-resources.md:8 +#: src/other-resources.md msgid "The Rust project hosts many resources. These cover Rust in general:" msgstr "Rust 專案中有許多資源。您可以透過這些資源瞭解 Rust 的一般概念:" -#: src/other-resources.md:10 +#: src/other-resources.md msgid "" "[The Rust Programming Language](https://doc.rust-lang.org/book/): the " "canonical free book about Rust. Covers the language in detail and includes a " @@ -19482,7 +21993,7 @@ msgstr "" "[The Rust Programming Language](https://doc.rust-lang.org/book/):Rust 的免費" "標準用書,詳細介紹這個語言的種種知識,也收錄了一些可供使用者建構的專案。" -#: src/other-resources.md:13 +#: src/other-resources.md msgid "" "[Rust By Example](https://doc.rust-lang.org/rust-by-example/): covers the " "Rust syntax via a series of examples which showcase different constructs. " @@ -19493,7 +22004,7 @@ msgstr "" "示範不同結構,進而介紹 Rust 語法。偶爾也會提供牛刀小試的練習,請您擴寫範例的" "程式碼。" -#: src/other-resources.md:17 +#: src/other-resources.md msgid "" "[Rust Standard Library](https://doc.rust-lang.org/std/): full documentation " "of the standard library for Rust." @@ -19501,7 +22012,7 @@ msgstr "" "[Rust Standard Library](https://doc.rust-lang.org/std/):Rust 標準程式庫的完" "整說明文件。" -#: src/other-resources.md:19 +#: src/other-resources.md msgid "" "[The Rust Reference](https://doc.rust-lang.org/reference/): an incomplete " "book which describes the Rust grammar and memory model." @@ -19509,11 +22020,11 @@ msgstr "" "[The Rust Reference](https://doc.rust-lang.org/reference/):本書並不完整,但" "會說明 Rust 文法和記憶體模型。" -#: src/other-resources.md:22 +#: src/other-resources.md msgid "More specialized guides hosted on the official Rust site:" msgstr "在 Rust 官方網站上還有更多專業指南:" -#: src/other-resources.md:24 +#: src/other-resources.md msgid "" "[The Rustonomicon](https://doc.rust-lang.org/nomicon/): covers unsafe Rust, " "including working with raw pointers and interfacing with other languages " @@ -19522,7 +22033,7 @@ msgstr "" "[The Rustonomicon](https://doc.rust-lang.org/nomicon/):說明不安全的 Rust,包" "括如何使用原始指標並與其他語言 (FFI) 互動。" -#: src/other-resources.md:27 +#: src/other-resources.md msgid "" "[Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/): " "covers the new asynchronous programming model which was introduced after the " @@ -19531,7 +22042,7 @@ msgstr "" "[Asynchronous Programming in Rust](https://rust-lang.github.io/async-book/):" "主要探討在 Rust 標準用書出版後問世的全新非同步程式設計模型。" -#: src/other-resources.md:30 +#: src/other-resources.md msgid "" "[The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/): " "an introduction to using Rust on embedded devices without an operating " @@ -19540,15 +22051,15 @@ msgstr "" "[The Embedded Rust Book](https://doc.rust-lang.org/stable/embedded-book/):說" "明如何在沒有作業系統的內嵌裝置上使用 Rust。" -#: src/other-resources.md:33 +#: src/other-resources.md msgid "Unofficial Learning Material" msgstr "非官方學習教材" -#: src/other-resources.md:35 +#: src/other-resources.md msgid "A small selection of other guides and tutorial for Rust:" msgstr "以下精選一些 Rust 的其他指南和教學課程:" -#: src/other-resources.md:37 +#: src/other-resources.md msgid "" "[Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/): covers Rust " "from the perspective of low-level C programmers." @@ -19556,7 +22067,7 @@ msgstr "" "[Learn Rust the Dangerous Way](http://cliffle.com/p/dangerust/):以低階 C 程" "式設計師的角度介紹 Rust。" -#: src/other-resources.md:39 +#: src/other-resources.md msgid "" "[Rust for Embedded C Programmers](https://docs.opentitan.org/doc/ug/" "rust_for_c/): covers Rust from the perspective of developers who write " @@ -19565,7 +22076,7 @@ msgstr "" "[Rust for Embedded C Programmers](https://docs.opentitan.org/doc/ug/" "rust_for_c/):從以 C 語言編寫韌體的開發人員角度介紹 Rust。" -#: src/other-resources.md:42 +#: src/other-resources.md msgid "" "[Rust for professionals](https://overexact.com/rust-for-professionals/): " "covers the syntax of Rust using side-by-side comparisons with other " @@ -19575,7 +22086,7 @@ msgstr "" "與其他語言 (例如 C、C++、Java、JavaScript 和 Python) 並列比較的方式介紹 Rust " "語法。" -#: src/other-resources.md:45 +#: src/other-resources.md msgid "" "[Rust on Exercism](https://exercism.org/tracks/rust): 100+ exercises to help " "you learn Rust." @@ -19583,7 +22094,7 @@ msgstr "" "[Rust on Exercism](https://exercism.org/tracks/rust):提供超過 100 項練習幫助" "您學習 Rust。" -#: src/other-resources.md:47 +#: src/other-resources.md msgid "" "[Ferrous Teaching Material](https://ferrous-systems.github.io/teaching-" "material/index.html): a series of small presentations covering both basic " @@ -19594,7 +22105,7 @@ msgstr "" "material/index.html):一系列精簡簡報,涵蓋 Rust 語言的基礎和進階部分,並說明 " "WebAssembly 和 async/await 等其他主題。" -#: src/other-resources.md:52 +#: src/other-resources.md msgid "" "[Beginner's Series to Rust](https://docs.microsoft.com/en-us/shows/beginners-" "series-to-rust/) and [Take your first steps with Rust](https://docs." @@ -19608,7 +22119,7 @@ msgstr "" "包含一套 35 部的影片,後者則是一套 11 個模組的課程,探討 Rust 語法和基本結" "構。" -#: src/other-resources.md:58 +#: src/other-resources.md msgid "" "[Learn Rust With Entirely Too Many Linked Lists](https://rust-unofficial." "github.io/too-many-lists/): in-depth exploration of Rust's memory management " @@ -19618,7 +22129,7 @@ msgstr "" "github.io/too-many-lists/):透過實作幾種不同型別的清單結構,深入探討 Rust 的" "記憶體管理規則。" -#: src/other-resources.md:63 +#: src/other-resources.md msgid "" "Please see the [Little Book of Rust Books](https://lborb.github.io/book/) " "for even more Rust books." @@ -19626,7 +22137,7 @@ msgstr "" "如需更多 Rust 相關書籍,請參閱 [Little Book of Rust Books](https://lborb." "github.io/book/)。" -#: src/credits.md:3 +#: src/credits.md msgid "" "The material here builds on top of the many great sources of Rust " "documentation. See the page on [other resources](other-resources.md) for a " @@ -19635,19 +22146,21 @@ msgstr "" "這份教材是以許多優質的 Rust 說明文件來源為基礎。請參閱 [其他資源](other-" "resources.md) 頁面,查看完整的實用資源清單。" -#: src/credits.md:7 +#: src/credits.md +#, fuzzy msgid "" "The material of Comprehensive Rust is licensed under the terms of the Apache " -"2.0 license, please see [`LICENSE`](../LICENSE) for details." +"2.0 license, please see [`LICENSE`](https://github.com/google/comprehensive-" +"rust/blob/main/LICENSE) for details." msgstr "" "Comprehensive Rust 的教材是根據 Apache 授權條款第 2.0 版取得授權,詳情請參閱 " "[`LICENSE`](../LICENSE) 頁面。" -#: src/credits.md:10 +#: src/credits.md msgid "Rust by Example" msgstr "Rust by Example" -#: src/credits.md:12 +#: src/credits.md msgid "" "Some examples and exercises have been copied and adapted from [Rust by " "Example](https://doc.rust-lang.org/rust-by-example/). Please see the " @@ -19658,11 +22171,11 @@ msgstr "" "example/),並經過調整。詳情請參閱 `third_party/rust-by-example/` 目錄,包括授" "權條款。" -#: src/credits.md:17 +#: src/credits.md msgid "Rust on Exercism" msgstr "Exercism 上的 Rust" -#: src/credits.md:19 +#: src/credits.md msgid "" "Some exercises have been copied and adapted from [Rust on Exercism](https://" "exercism.org/tracks/rust). Please see the `third_party/rust-on-exercism/` " @@ -19672,11 +22185,11 @@ msgstr "" "內容,並經過調整。詳情請參閱 `third_party/rust-on-exercism/` 目錄,包括授權條" "款。" -#: src/credits.md:24 +#: src/credits.md msgid "CXX" msgstr "CXX" -#: src/credits.md:26 +#: src/credits.md msgid "" "The [Interoperability with C++](android/interoperability/cpp.md) section " "uses an image from [CXX](https://cxx.rs/). Please see the `third_party/cxx/` " @@ -19686,2915 +22199,4668 @@ msgstr "" "的圖片是出自 [CXX](https://cxx.rs/)。詳情請參閱 `third_party/cxx/` 目錄,包括" "授權條款。" -#: src/exercises/solutions.md:3 -msgid "You will find solutions to the exercises on the following pages." -msgstr "您可以在以下幾頁查看練習的解決方案。" - -#: src/exercises/solutions.md:5 -msgid "" -"Feel free to ask questions about the solutions [on GitHub](https://github." -"com/google/comprehensive-rust/discussions). Let us know if you have a " -"different or better solution than what is presented here." -msgstr "" -"歡迎[前往 GitHub](https://github.com/google/comprehensive-rust/discussions)針" -"對解決方案提問。如果您有與本書不同或更好的解決方案,請告訴我們。" - -#: src/exercises/solutions.md:10 -msgid "" -"**Note:** Please ignore the `// ANCHOR: label` and `// ANCHOR_END: label` " -"comments you see in the solutions. They are there to make it possible to re-" -"use parts of the solutions as the exercises." -msgstr "" -"**注意:**請忽略解決方案中的 `// ANCHOR: label` 和 `// ANCHOR_END: label` 註" -"解。之所以有這些註解,是要方便您重複利用解決方案的某些部分來練習。" - -#: src/exercises/day-1/solutions-morning.md:1 -msgid "Day 1 Morning Exercises" -msgstr "第 1 天:上午練習" - -#: src/exercises/day-1/solutions-morning.md:5 -msgid "([back to exercise](for-loops.md))" -msgstr "([返回練習](for-loops.md))" - -#: src/exercises/day-1/solutions-morning.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: transpose\n" -"fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {\n" -" // ANCHOR_END: transpose\n" -" let mut result = [[0; 3]; 3];\n" -" for i in 0..3 {\n" -" for j in 0..3 {\n" -" result[j][i] = matrix[i][j];\n" -" }\n" -" }\n" -" return result;\n" -"}\n" -"\n" -"// ANCHOR: pretty_print\n" -"fn pretty_print(matrix: &[[i32; 3]; 3]) {\n" -" // ANCHOR_END: pretty_print\n" -" for row in matrix {\n" -" println!(\"{row:?}\");\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: tests\n" -"#[test]\n" -"fn test_transpose() {\n" -" let matrix = [\n" -" [101, 102, 103], //\n" -" [201, 202, 203],\n" -" [301, 302, 303],\n" -" ];\n" -" let transposed = transpose(matrix);\n" -" assert_eq!(\n" -" transposed,\n" -" [\n" -" [101, 201, 301], //\n" -" [102, 202, 302],\n" -" [103, 203, 303],\n" -" ]\n" -" );\n" -"}\n" -"// ANCHOR_END: tests\n" -"\n" -"// ANCHOR: main\n" -"fn main() {\n" -" let matrix = [\n" -" [101, 102, 103], // <-- the comment makes rustfmt add a newline\n" -" [201, 202, 203],\n" -" [301, 302, 303],\n" -" ];\n" -"\n" -" println!(\"matrix:\");\n" -" pretty_print(&matrix);\n" -"\n" -" let transposed = transpose(matrix);\n" -" println!(\"transposed:\");\n" -" pretty_print(&transposed);\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/solutions-morning.md:78 -msgid "Bonus question" -msgstr "加分題" - -#: src/exercises/day-1/solutions-morning.md:80 -msgid "" -"It requires more advanced concepts. It might seem that we could use a slice-" -"of-slices (`&[&[i32]]`) as the input type to transpose and thus make our " -"function handle any size of matrix. However, this quickly breaks down: the " -"return type cannot be `&[&[i32]]` since it needs to own the data you return." -msgstr "" -"這需要用到更進階的概念。表面上看起來我們可以使用多維度切片 (`&[&[i32]]`) 做為" -"轉置的輸入型別,進而讓函式處理任何大小的矩陣。但實際上這很快就會失敗,也就是" -"說傳回型別不能是 `&[&[i32]]`,因為它需要擁有您傳回的資料。" - -#: src/exercises/day-1/solutions-morning.md:82 -msgid "" -"You can attempt to use something like `Vec>`, but this doesn't work " -"out-of-the-box either: it's hard to convert from `Vec>` to " -"`&[&[i32]]` so now you cannot easily use `pretty_print` either." -msgstr "" -"您可以嘗試使用 `Vec>` 這類代碼,但這也不能立即見效,因為從 " -"`Vec>` 轉換成 `&[&[i32]]` 並不容易,因此您現在也無法輕易使用 " -"`pretty_print`。" - -#: src/exercises/day-1/solutions-morning.md:84 -msgid "" -"Once we get to traits and generics, we'll be able to use the [`std::convert::" -"AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html) trait to " -"abstract over anything that can be referenced as a slice." -msgstr "" -"一旦瞭解特徵和泛型,我們就能使用 [`std::convert::AsRef`](https://doc.rust-" -"lang.org/std/convert/trait.AsRef.html) 特徵,對任何可當做切片參照的資料進行抽" -"象化。" - -#: src/exercises/day-1/solutions-morning.md:86 -msgid "" -"```rust\n" -"use std::convert::AsRef;\n" -"use std::fmt::Debug;\n" -"\n" -"fn pretty_print(matrix: Matrix)\n" -"where\n" -" T: Debug,\n" -" // A line references a slice of items\n" -" Line: AsRef<[T]>,\n" -" // A matrix references a slice of lines\n" -" Matrix: AsRef<[Line]>\n" -"{\n" -" for row in matrix.as_ref() {\n" -" println!(\"{:?}\", row.as_ref());\n" -" }\n" -"}\n" -"\n" -"fn main() {\n" -" // &[&[i32]]\n" -" pretty_print(&[&[1, 2, 3], &[4, 5, 6], &[7, 8, 9]]);\n" -" // [[&str; 2]; 2]\n" -" pretty_print([[\"a\", \"b\"], [\"c\", \"d\"]]);\n" -" // Vec>\n" -" pretty_print(vec![vec![1, 2], vec![3, 4]]);\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-1/solutions-morning.md:113 -msgid "" -"In addition, the type itself would not enforce that the child slices are of " -"the same length, so such variable could contain an invalid matrix." -msgstr "" -"此外,型別本身不會強制規定子項切片的長度必須相同,因此這類變數可能含有無效的" -"矩陣。" - -#: src/exercises/day-1/solutions-afternoon.md:1 -msgid "Day 1 Afternoon Exercises" -msgstr "第 1 天:下午練習" - -#: src/exercises/day-2/solutions-morning.md:5 -msgid "([back to exercise](book-library.md))" -msgstr "([返回練習](book-library.md))" - -#: src/exercises/day-1/solutions-afternoon.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: setup\n" -"struct Library {\n" -" books: Vec,\n" -"}\n" -"\n" -"struct Book {\n" -" title: String,\n" -" year: u16,\n" -"}\n" -"\n" -"impl Book {\n" -" // This is a constructor, used below.\n" -" fn new(title: &str, year: u16) -> Book {\n" -" Book {\n" -" title: String::from(title),\n" -" year,\n" -" }\n" -" }\n" -"}\n" -"\n" -"// Implement the methods below. Update the `self` parameter to\n" -"// indicate the method's required level of ownership over the object:\n" -"//\n" -"// - `&self` for shared read-only access,\n" -"// - `&mut self` for unique and mutable access,\n" -"// - `self` for unique access by value.\n" -"impl Library {\n" -" // ANCHOR_END: setup\n" -"\n" -" // ANCHOR: Library_new\n" -" fn new() -> Library {\n" -" // ANCHOR_END: Library_new\n" -" Library { books: Vec::new() }\n" -" }\n" -"\n" -" // ANCHOR: Library_len\n" -" //fn len(self) -> usize {\n" -" // todo!(\"Return the length of `self.books`\")\n" -" //}\n" -" // ANCHOR_END: Library_len\n" -" fn len(&self) -> usize {\n" -" self.books.len()\n" -" }\n" -"\n" -" // ANCHOR: Library_is_empty\n" -" //fn is_empty(self) -> bool {\n" -" // todo!(\"Return `true` if `self.books` is empty\")\n" -" //}\n" -" // ANCHOR_END: Library_is_empty\n" -" fn is_empty(&self) -> bool {\n" -" self.books.is_empty()\n" -" }\n" -"\n" -" // ANCHOR: Library_add_book\n" -" //fn add_book(self, book: Book) {\n" -" // todo!(\"Add a new book to `self.books`\")\n" -" //}\n" -" // ANCHOR_END: Library_add_book\n" -" fn add_book(&mut self, book: Book) {\n" -" self.books.push(book)\n" -" }\n" -"\n" -" // ANCHOR: Library_print_books\n" -" //fn print_books(self) {\n" -" // todo!(\"Iterate over `self.books` and each book's title and " -"year\")\n" -" //}\n" -" // ANCHOR_END: Library_print_books\n" -" fn print_books(&self) {\n" -" for book in &self.books {\n" -" println!(\"{}, published in {}\", book.title, book.year);\n" -" }\n" -" }\n" -"\n" -" // ANCHOR: Library_oldest_book\n" -" //fn oldest_book(self) -> Option<&Book> {\n" -" // todo!(\"Return a reference to the oldest book (if any)\")\n" -" //}\n" -" // ANCHOR_END: Library_oldest_book\n" -" fn oldest_book(&self) -> Option<&Book> {\n" -" // Using a closure and a built-in method:\n" -" // self.books.iter().min_by_key(|book| book.year)\n" -"\n" -" // Longer hand-written solution:\n" -" let mut oldest: Option<&Book> = None;\n" -" for book in self.books.iter() {\n" -" if oldest.is_none() || book.year < oldest.unwrap().year {\n" -" oldest = Some(book);\n" -" }\n" -" }\n" -"\n" -" oldest\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: main\n" -"// This shows the desired behavior. Uncomment the code below and\n" -"// implement the missing methods. You will need to update the\n" -"// method signatures, including the \"self\" parameter! You may\n" -"// also need to update the variable bindings within main.\n" -"fn main() {\n" -" let library = Library::new();\n" -"\n" -" //println!(\"The library is empty: {}\", library.is_empty());\n" -" //\n" -" //library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" //library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" //\n" -" //println!(\"The library is no longer empty: {}\", library.is_empty());\n" -" //\n" -" //\n" -" //library.print_books();\n" -" //\n" -" //match library.oldest_book() {\n" -" // Some(book) => println!(\"The oldest book is {}\", book.title),\n" -" // None => println!(\"The library is empty!\"),\n" -" //}\n" -" //\n" -" //println!(\"The library has {} books\", library.len());\n" -" //library.print_books();\n" -"}\n" -"// ANCHOR_END: main\n" -"\n" -"#[test]\n" -"fn test_library_len() {\n" -" let mut library = Library::new();\n" -" assert_eq!(library.len(), 0);\n" -" assert!(library.is_empty());\n" -"\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" assert_eq!(library.len(), 2);\n" -" assert!(!library.is_empty());\n" -"}\n" -"\n" -"#[test]\n" -"fn test_library_is_empty() {\n" -" let mut library = Library::new();\n" -" assert!(library.is_empty());\n" -"\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" assert!(!library.is_empty());\n" -"}\n" -"\n" -"#[test]\n" -"fn test_library_print_books() {\n" -" let mut library = Library::new();\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" // We could try and capture stdout, but let us just call the\n" -" // method to start with.\n" -" library.print_books();\n" -"}\n" -"\n" -"#[test]\n" -"fn test_library_oldest_book() {\n" -" let mut library = Library::new();\n" -" assert!(library.oldest_book().is_none());\n" -"\n" -" library.add_book(Book::new(\"Lord of the Rings\", 1954));\n" -" assert_eq!(\n" -" library.oldest_book().map(|b| b.title.as_str()),\n" -" Some(\"Lord of the Rings\")\n" -" );\n" -"\n" -" library.add_book(Book::new(\"Alice's Adventures in Wonderland\", " -"1865));\n" -" assert_eq!(\n" -" library.oldest_book().map(|b| b.title.as_str()),\n" -" Some(\"Alice's Adventures in Wonderland\")\n" -" );\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/day-2/solutions-morning.md:1 -msgid "Day 2 Morning Exercises" -msgstr "第 2 天:上午練習" - -#: src/exercises/day-3/solutions-morning.md:177 -msgid "([back to exercise](points-polygons.md))" -msgstr "([返回練習](points-polygons.md))" - -#: src/exercises/day-2/solutions-morning.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"#[derive(Debug, Copy, Clone, PartialEq, Eq)]\n" -"// ANCHOR: Point\n" -"pub struct Point {\n" -" // ANCHOR_END: Point\n" -" x: i32,\n" -" y: i32,\n" -"}\n" -"\n" -"// ANCHOR: Point-impl\n" -"impl Point {\n" -" // ANCHOR_END: Point-impl\n" -" pub fn new(x: i32, y: i32) -> Point {\n" -" Point { x, y }\n" -" }\n" -"\n" -" pub fn magnitude(self) -> f64 {\n" -" f64::from(self.x.pow(2) + self.y.pow(2)).sqrt()\n" -" }\n" -"\n" -" pub fn dist(self, other: Point) -> f64 {\n" -" (self - other).magnitude()\n" -" }\n" -"}\n" -"\n" -"impl std::ops::Add for Point {\n" -" type Output = Self;\n" -"\n" -" fn add(self, other: Self) -> Self::Output {\n" -" Self {\n" -" x: self.x + other.x,\n" -" y: self.y + other.y,\n" -" }\n" -" }\n" -"}\n" -"\n" -"impl std::ops::Sub for Point {\n" -" type Output = Self;\n" -"\n" -" fn sub(self, other: Self) -> Self::Output {\n" -" Self {\n" -" x: self.x - other.x,\n" -" y: self.y - other.y,\n" -" }\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Polygon\n" -"pub struct Polygon {\n" -" // ANCHOR_END: Polygon\n" -" points: Vec,\n" -"}\n" -"\n" -"// ANCHOR: Polygon-impl\n" -"impl Polygon {\n" -" // ANCHOR_END: Polygon-impl\n" -" pub fn new() -> Polygon {\n" -" Polygon { points: Vec::new() }\n" -" }\n" -"\n" -" pub fn add_point(&mut self, point: Point) {\n" -" self.points.push(point);\n" -" }\n" -"\n" -" pub fn left_most_point(&self) -> Option {\n" -" self.points.iter().min_by_key(|p| p.x).copied()\n" -" }\n" -"\n" -" pub fn iter(&self) -> impl Iterator {\n" -" self.points.iter()\n" -" }\n" -"\n" -" pub fn length(&self) -> f64 {\n" -" if self.points.is_empty() {\n" -" return 0.0;\n" -" }\n" -"\n" -" let mut result = 0.0;\n" -" let mut last_point = self.points[0];\n" -" for point in &self.points[1..] {\n" -" result += last_point.dist(*point);\n" -" last_point = *point;\n" -" }\n" -" result += last_point.dist(self.points[0]);\n" -" result\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Circle\n" -"pub struct Circle {\n" -" // ANCHOR_END: Circle\n" -" center: Point,\n" -" radius: i32,\n" -"}\n" -"\n" -"// ANCHOR: Circle-impl\n" -"impl Circle {\n" -" // ANCHOR_END: Circle-impl\n" -" pub fn new(center: Point, radius: i32) -> Circle {\n" -" Circle { center, radius }\n" -" }\n" -"\n" -" pub fn circumference(&self) -> f64 {\n" -" 2.0 * std::f64::consts::PI * f64::from(self.radius)\n" -" }\n" -"\n" -" pub fn dist(&self, other: &Self) -> f64 {\n" -" self.center.dist(other.center)\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Shape\n" -"pub enum Shape {\n" -" Polygon(Polygon),\n" -" Circle(Circle),\n" -"}\n" -"// ANCHOR_END: Shape\n" -"\n" -"impl From for Shape {\n" -" fn from(poly: Polygon) -> Self {\n" -" Shape::Polygon(poly)\n" -" }\n" -"}\n" -"\n" -"impl From for Shape {\n" -" fn from(circle: Circle) -> Self {\n" -" Shape::Circle(circle)\n" -" }\n" -"}\n" -"\n" -"impl Shape {\n" -" pub fn perimeter(&self) -> f64 {\n" -" match self {\n" -" Shape::Polygon(poly) => poly.length(),\n" -" Shape::Circle(circle) => circle.circumference(),\n" -" }\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: unit-tests\n" -"#[cfg(test)]\n" -"mod tests {\n" -" use super::*;\n" -"\n" -" fn round_two_digits(x: f64) -> f64 {\n" -" (x * 100.0).round() / 100.0\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_magnitude() {\n" -" let p1 = Point::new(12, 13);\n" -" assert_eq!(round_two_digits(p1.magnitude()), 17.69);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_dist() {\n" -" let p1 = Point::new(10, 10);\n" -" let p2 = Point::new(14, 13);\n" -" assert_eq!(round_two_digits(p1.dist(p2)), 5.00);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_point_add() {\n" -" let p1 = Point::new(16, 16);\n" -" let p2 = p1 + Point::new(-4, 3);\n" -" assert_eq!(p2, Point::new(12, 19));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_left_most_point() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -" assert_eq!(poly.left_most_point(), Some(p1));\n" -" }\n" -"\n" -" #[test]\n" -" fn test_polygon_iter() {\n" -" let p1 = Point::new(12, 13);\n" -" let p2 = Point::new(16, 16);\n" -"\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(p1);\n" -" poly.add_point(p2);\n" -"\n" -" let points = poly.iter().cloned().collect::>();\n" -" assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);\n" -" }\n" -"\n" -" #[test]\n" -" fn test_shape_perimeters() {\n" -" let mut poly = Polygon::new();\n" -" poly.add_point(Point::new(12, 13));\n" -" poly.add_point(Point::new(17, 11));\n" -" poly.add_point(Point::new(16, 16));\n" -" let shapes = vec![\n" -" Shape::from(poly),\n" -" Shape::from(Circle::new(Point::new(10, 20), 5)),\n" -" ];\n" -" let perimeters = shapes\n" -" .iter()\n" -" .map(Shape::perimeter)\n" -" .map(round_two_digits)\n" -" .collect::>();\n" -" assert_eq!(perimeters, vec![15.48, 31.42]);\n" -" }\n" -"}\n" -"// ANCHOR_END: unit-tests\n" -"\n" -"fn main() {}\n" -"```" -msgstr "" - -#: src/exercises/day-2/solutions-afternoon.md:1 -msgid "Day 2 Afternoon Exercises" -msgstr "第 2 天:下午練習" - -#: src/exercises/day-1/solutions-afternoon.md:5 -msgid "([back to exercise](luhn.md))" -msgstr "([返回練習](luhn.md))" - -#: src/exercises/day-2/solutions-afternoon.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: luhn\n" -"pub fn luhn(cc_number: &str) -> bool {\n" -" // ANCHOR_END: luhn\n" -" let mut digits_seen = 0;\n" -" let mut sum = 0;\n" -" for (i, ch) in cc_number.chars().rev().filter(|&ch| ch != ' ')." -"enumerate() {\n" -" match ch.to_digit(10) {\n" -" Some(d) => {\n" -" sum += if i % 2 == 1 {\n" -" let dd = d * 2;\n" -" dd / 10 + dd % 10\n" -" } else {\n" -" d\n" -" };\n" -" digits_seen += 1;\n" -" }\n" -" None => return false,\n" -" }\n" -" }\n" -"\n" -" if digits_seen < 2 {\n" -" return false;\n" -" }\n" -"\n" -" sum % 10 == 0\n" -"}\n" -"\n" -"fn main() {\n" -" let cc_number = \"1234 5678 1234 5670\";\n" -" println!(\n" -" \"Is {cc_number} a valid credit card number? {}\",\n" -" if luhn(cc_number) { \"yes\" } else { \"no\" }\n" -" );\n" -"}\n" -"\n" -"// ANCHOR: unit-tests\n" -"#[test]\n" -"fn test_non_digit_cc_number() {\n" -" assert!(!luhn(\"foo\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_empty_cc_number() {\n" -" assert!(!luhn(\"\"));\n" -" assert!(!luhn(\" \"));\n" -" assert!(!luhn(\" \"));\n" -" assert!(!luhn(\" \"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_single_digit_cc_number() {\n" -" assert!(!luhn(\"0\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_two_digit_cc_number() {\n" -" assert!(luhn(\" 0 0 \"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_valid_cc_number() {\n" -" assert!(luhn(\"4263 9826 4026 9299\"));\n" -" assert!(luhn(\"4539 3195 0343 6467\"));\n" -" assert!(luhn(\"7992 7398 713\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_invalid_cc_number() {\n" -" assert!(!luhn(\"4223 9826 4026 9299\"));\n" -" assert!(!luhn(\"4539 3195 0343 6476\"));\n" -" assert!(!luhn(\"8273 1232 7352 0569\"));\n" -"}\n" -"// ANCHOR_END: unit-tests\n" -"```" -msgstr "" - -#: src/exercises/day-2/solutions-afternoon.md:5 -msgid "([back to exercise](strings-iterators.md))" -msgstr "([返回練習](strings-iterators.md))" - -#: src/exercises/day-2/solutions-afternoon.md:101 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: prefix_matches\n" -"pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {\n" -" // ANCHOR_END: prefix_matches\n" -" let prefixes = prefix.split('/');\n" -" let request_paths = request_path\n" -" .split('/')\n" -" .map(|p| Some(p))\n" -" .chain(std::iter::once(None));\n" -"\n" -" for (prefix, request_path) in prefixes.zip(request_paths) {\n" -" match request_path {\n" -" Some(request_path) => {\n" -" if (prefix != \"*\") && (prefix != request_path) {\n" -" return false;\n" -" }\n" -" }\n" -" None => return false,\n" -" }\n" -" }\n" -" true\n" -"}\n" -"\n" -"// ANCHOR: unit-tests\n" -"#[test]\n" -"fn test_matches_without_wildcard() {\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers\"));\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/" -"abc-123\"));\n" -" assert!(prefix_matches(\"/v1/publishers\", \"/v1/publishers/abc/" -"books\"));\n" -"\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1\"));\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/publishersBooks\"));\n" -" assert!(!prefix_matches(\"/v1/publishers\", \"/v1/parent/" -"publishers\"));\n" -"}\n" -"\n" -"#[test]\n" -"fn test_matches_with_wildcard() {\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/books\"\n" -" ));\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/bar/books\"\n" -" ));\n" -" assert!(prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/books/book1\"\n" -" ));\n" -"\n" -" assert!(!prefix_matches(\"/v1/publishers/*/books\", \"/v1/" -"publishers\"));\n" -" assert!(!prefix_matches(\n" -" \"/v1/publishers/*/books\",\n" -" \"/v1/publishers/foo/booksByAuthor\"\n" -" ));\n" -"}\n" -"// ANCHOR_END: unit-tests\n" -"\n" -"fn main() {}\n" -"```" -msgstr "" - -#: src/exercises/day-3/solutions-morning.md:1 -msgid "Day 3 Morning Exercise" -msgstr "第 3 天:上午練習" - -#: src/exercises/day-3/solutions-morning.md:5 -msgid "([back to exercise](simple-gui.md))" -msgstr "([返回練習](simple-gui.md))" - -#: src/exercises/day-3/solutions-morning.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: setup\n" -"pub trait Widget {\n" -" /// Natural width of `self`.\n" -" fn width(&self) -> usize;\n" -"\n" -" /// Draw the widget into a buffer.\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write);\n" -"\n" -" /// Draw the widget on standard output.\n" -" fn draw(&self) {\n" -" let mut buffer = String::new();\n" -" self.draw_into(&mut buffer);\n" -" println!(\"{buffer}\");\n" -" }\n" -"}\n" -"\n" -"pub struct Label {\n" -" label: String,\n" -"}\n" -"\n" -"impl Label {\n" -" fn new(label: &str) -> Label {\n" -" Label {\n" -" label: label.to_owned(),\n" -" }\n" -" }\n" -"}\n" -"\n" -"pub struct Button {\n" -" label: Label,\n" -" callback: Box,\n" -"}\n" -"\n" -"impl Button {\n" -" fn new(label: &str, callback: Box) -> Button {\n" -" Button {\n" -" label: Label::new(label),\n" -" callback,\n" -" }\n" -" }\n" -"}\n" -"\n" -"pub struct Window {\n" -" title: String,\n" -" widgets: Vec>,\n" -"}\n" -"\n" -"impl Window {\n" -" fn new(title: &str) -> Window {\n" -" Window {\n" -" title: title.to_owned(),\n" -" widgets: Vec::new(),\n" -" }\n" -" }\n" -"\n" -" fn add_widget(&mut self, widget: Box) {\n" -" self.widgets.push(widget);\n" -" }\n" -"\n" -" fn inner_width(&self) -> usize {\n" -" std::cmp::max(\n" -" self.title.chars().count(),\n" -" self.widgets.iter().map(|w| w.width()).max().unwrap_or(0),\n" -" )\n" -" }\n" -"}\n" -"\n" -"// ANCHOR_END: setup\n" -"\n" -"// ANCHOR: Window-width\n" -"impl Widget for Window {\n" -" fn width(&self) -> usize {\n" -" // ANCHOR_END: Window-width\n" -" // Add 4 paddings for borders\n" -" self.inner_width() + 4\n" -" }\n" -"\n" -" // ANCHOR: Window-draw_into\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" // ANCHOR_END: Window-draw_into\n" -" let mut inner = String::new();\n" -" for widget in &self.widgets {\n" -" widget.draw_into(&mut inner);\n" -" }\n" -"\n" -" let inner_width = self.inner_width();\n" -"\n" -" // TODO: after learning about error handling, you can change\n" -" // draw_into to return Result<(), std::fmt::Error>. Then use\n" -" // the ?-operator here instead of .unwrap().\n" -" writeln!(buffer, \"+-{:- usize {\n" -" // ANCHOR_END: Button-width\n" -" self.label.width() + 8 // add a bit of padding\n" -" }\n" -"\n" -" // ANCHOR: Button-draw_into\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" // ANCHOR_END: Button-draw_into\n" -" let width = self.width();\n" -" let mut label = String::new();\n" -" self.label.draw_into(&mut label);\n" -"\n" -" writeln!(buffer, \"+{:- usize {\n" -" // ANCHOR_END: Label-width\n" -" self.label\n" -" .lines()\n" -" .map(|line| line.chars().count())\n" -" .max()\n" -" .unwrap_or(0)\n" -" }\n" -"\n" -" // ANCHOR: Label-draw_into\n" -" fn draw_into(&self, buffer: &mut dyn std::fmt::Write) {\n" -" // ANCHOR_END: Label-draw_into\n" -" writeln!(buffer, \"{}\", &self.label).unwrap();\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: main\n" -"fn main() {\n" -" let mut window = Window::new(\"Rust GUI Demo 1.23\");\n" -" window.add_widget(Box::new(Label::new(\"This is a small text GUI demo." -"\")));\n" -" window.add_widget(Box::new(Button::new(\n" -" \"Click me!\",\n" -" Box::new(|| println!(\"You clicked the button!\")),\n" -" )));\n" -" window.draw();\n" -"}\n" -"// ANCHOR_END: main\n" -"```" -msgstr "" - -#: src/exercises/day-3/solutions-afternoon.md:1 -msgid "Day 3 Afternoon Exercises" -msgstr "第 3 天:下午練習" - -#: src/exercises/day-3/solutions-afternoon.md:5 -msgid "([back to exercise](safe-ffi-wrapper.md))" -msgstr "([返回練習](safe-ffi-wrapper.md))" - -#: src/exercises/day-3/solutions-afternoon.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: ffi\n" -"mod ffi {\n" -" use std::os::raw::{c_char, c_int};\n" -" #[cfg(not(target_os = \"macos\"))]\n" -" use std::os::raw::{c_long, c_ulong, c_ushort};\n" -"\n" -" // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html.\n" -" #[repr(C)]\n" -" pub struct DIR {\n" -" _data: [u8; 0],\n" -" _marker: core::marker::PhantomData<(*mut u8, core::marker::" -"PhantomPinned)>,\n" -" }\n" -"\n" -" // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-" -"gnu.\n" -" #[cfg(not(target_os = \"macos\"))]\n" -" #[repr(C)]\n" -" pub struct dirent {\n" -" pub d_ino: c_long,\n" -" pub d_off: c_ulong,\n" -" pub d_reclen: c_ushort,\n" -" pub d_type: c_char,\n" -" pub d_name: [c_char; 256],\n" -" }\n" -"\n" -" // Layout as per man entry for dirent\n" -" #[cfg(target_os = \"macos\")]\n" -" #[repr(C)]\n" -" pub struct dirent {\n" -" pub d_ino: u64,\n" -" pub d_seekoff: u64,\n" -" pub d_reclen: u16,\n" -" pub d_namlen: u16,\n" -" pub d_type: u8,\n" -" pub d_name: [c_char; 1024],\n" -" }\n" -"\n" -" extern \"C\" {\n" -" pub fn opendir(s: *const c_char) -> *mut DIR;\n" -" pub fn readdir(s: *mut DIR) -> *const dirent;\n" -" pub fn closedir(s: *mut DIR) -> c_int;\n" -" }\n" -"}\n" -"\n" -"use std::ffi::{CStr, CString, OsStr, OsString};\n" -"use std::os::unix::ffi::OsStrExt;\n" -"\n" -"#[derive(Debug)]\n" -"struct DirectoryIterator {\n" -" path: CString,\n" -" dir: *mut ffi::DIR,\n" -"}\n" -"// ANCHOR_END: ffi\n" -"\n" -"// ANCHOR: DirectoryIterator\n" -"impl DirectoryIterator {\n" -" fn new(path: &str) -> Result {\n" -" // Call opendir and return a Ok value if that worked,\n" -" // otherwise return Err with a message.\n" -" // ANCHOR_END: DirectoryIterator\n" -" let path = CString::new(path).map_err(|err| format!(\"Invalid path: " -"{err}\"))?;\n" -" // SAFETY: path.as_ptr() cannot be NULL.\n" -" let dir = unsafe { ffi::opendir(path.as_ptr()) };\n" -" if dir.is_null() {\n" -" Err(format!(\"Could not open {:?}\", path))\n" -" } else {\n" -" Ok(DirectoryIterator { path, dir })\n" -" }\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Iterator\n" -"impl Iterator for DirectoryIterator {\n" -" type Item = OsString;\n" -" fn next(&mut self) -> Option {\n" -" // Keep calling readdir until we get a NULL pointer back.\n" -" // ANCHOR_END: Iterator\n" -" // SAFETY: self.dir is never NULL.\n" -" let dirent = unsafe { ffi::readdir(self.dir) };\n" -" if dirent.is_null() {\n" -" // We have reached the end of the directory.\n" -" return None;\n" -" }\n" -" // SAFETY: dirent is not NULL and dirent.d_name is NUL\n" -" // terminated.\n" -" let d_name = unsafe { CStr::from_ptr((*dirent).d_name.as_ptr()) };\n" -" let os_str = OsStr::from_bytes(d_name.to_bytes());\n" -" Some(os_str.to_owned())\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: Drop\n" -"impl Drop for DirectoryIterator {\n" -" fn drop(&mut self) {\n" -" // Call closedir as needed.\n" -" // ANCHOR_END: Drop\n" -" if !self.dir.is_null() {\n" -" // SAFETY: self.dir is not NULL.\n" -" if unsafe { ffi::closedir(self.dir) } != 0 {\n" -" panic!(\"Could not close {:?}\", self.path);\n" -" }\n" -" }\n" -" }\n" -"}\n" -"\n" -"// ANCHOR: main\n" -"fn main() -> Result<(), String> {\n" -" let iter = DirectoryIterator::new(\".\")?;\n" -" println!(\"files: {:#?}\", iter.collect::>());\n" -" Ok(())\n" -"}\n" -"// ANCHOR_END: main\n" -"\n" -"#[cfg(test)]\n" -"mod tests {\n" -" use super::*;\n" -" use std::error::Error;\n" -"\n" -" #[test]\n" -" fn test_nonexisting_directory() {\n" -" let iter = DirectoryIterator::new(\"no-such-directory\");\n" -" assert!(iter.is_err());\n" -" }\n" -"\n" -" #[test]\n" -" fn test_empty_directory() -> Result<(), Box> {\n" -" let tmp = tempfile::TempDir::new()?;\n" -" let iter = DirectoryIterator::new(\n" -" tmp.path().to_str().ok_or(\"Non UTF-8 character in path\")?,\n" -" )?;\n" -" let mut entries = iter.collect::>();\n" -" entries.sort();\n" -" assert_eq!(entries, &[\".\", \"..\"]);\n" -" Ok(())\n" -" }\n" -"\n" -" #[test]\n" -" fn test_nonempty_directory() -> Result<(), Box> {\n" -" let tmp = tempfile::TempDir::new()?;\n" -" std::fs::write(tmp.path().join(\"foo.txt\"), \"The Foo " -"Diaries\\n\")?;\n" -" std::fs::write(tmp.path().join(\"bar.png\"), \"\\n\")?;\n" -" std::fs::write(tmp.path().join(\"crab.rs\"), \"//! Crab\\n\")?;\n" -" let iter = DirectoryIterator::new(\n" -" tmp.path().to_str().ok_or(\"Non UTF-8 character in path\")?,\n" -" )?;\n" -" let mut entries = iter.collect::>();\n" -" entries.sort();\n" -" assert_eq!(entries, &[\".\", \"..\", \"bar.png\", \"crab.rs\", \"foo." -"txt\"]);\n" -" Ok(())\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/solutions-morning.md:1 -msgid "Bare Metal Rust Morning Exercise" -msgstr "Rust 裸機開發:上午練習" - -#: src/exercises/bare-metal/solutions-morning.md:5 -msgid "([back to exercise](compass.md))" -msgstr "([返回練習](compass.md))" - -#: src/exercises/bare-metal/solutions-morning.md:7 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: top\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"extern crate panic_halt as _;\n" -"\n" -"use core::fmt::Write;\n" -"use cortex_m_rt::entry;\n" -"// ANCHOR_END: top\n" -"use core::cmp::{max, min};\n" -"use lsm303agr::{AccelOutputDataRate, Lsm303agr, MagOutputDataRate};\n" -"use microbit::display::blocking::Display;\n" -"use microbit::hal::prelude::*;\n" -"use microbit::hal::twim::Twim;\n" -"use microbit::hal::uarte::{Baudrate, Parity, Uarte};\n" -"use microbit::hal::Timer;\n" -"use microbit::pac::twim0::frequency::FREQUENCY_A;\n" -"use microbit::Board;\n" -"\n" -"const COMPASS_SCALE: i32 = 30000;\n" -"const ACCELEROMETER_SCALE: i32 = 700;\n" -"\n" -"// ANCHOR: main\n" -"#[entry]\n" -"fn main() -> ! {\n" -" let board = Board::take().unwrap();\n" -"\n" -" // Configure serial port.\n" -" let mut serial = Uarte::new(\n" -" board.UARTE0,\n" -" board.uart.into(),\n" -" Parity::EXCLUDED,\n" -" Baudrate::BAUD115200,\n" -" );\n" -"\n" -" // Set up the I2C controller and Inertial Measurement Unit.\n" -" // ANCHOR_END: main\n" -" writeln!(serial, \"Setting up IMU...\").unwrap();\n" -" let i2c = Twim::new(board.TWIM0, board.i2c_internal.into(), FREQUENCY_A::" -"K100);\n" -" let mut imu = Lsm303agr::new_with_i2c(i2c);\n" -" imu.init().unwrap();\n" -" imu.set_mag_odr(MagOutputDataRate::Hz50).unwrap();\n" -" imu.set_accel_odr(AccelOutputDataRate::Hz50).unwrap();\n" -" let mut imu = imu.into_mag_continuous().ok().unwrap();\n" -"\n" -" // Set up display and timer.\n" -" let mut timer = Timer::new(board.TIMER0);\n" -" let mut display = Display::new(board.display_pins);\n" -"\n" -" let mut mode = Mode::Compass;\n" -" let mut button_pressed = false;\n" -"\n" -" // ANCHOR: loop\n" -" writeln!(serial, \"Ready.\").unwrap();\n" -"\n" -" loop {\n" -" // Read compass data and log it to the serial port.\n" -" // ANCHOR_END: loop\n" -" while !(imu.mag_status().unwrap().xyz_new_data\n" -" && imu.accel_status().unwrap().xyz_new_data)\n" -" {}\n" -" let compass_reading = imu.mag_data().unwrap();\n" -" let accelerometer_reading = imu.accel_data().unwrap();\n" -" writeln!(\n" -" serial,\n" -" \"{},{},{}\\t{},{},{}\",\n" -" compass_reading.x,\n" -" compass_reading.y,\n" -" compass_reading.z,\n" -" accelerometer_reading.x,\n" -" accelerometer_reading.y,\n" -" accelerometer_reading.z,\n" -" )\n" -" .unwrap();\n" -"\n" -" let mut image = [[0; 5]; 5];\n" -" let (x, y) = match mode {\n" -" Mode::Compass => (\n" -" scale(-compass_reading.x, -COMPASS_SCALE, COMPASS_SCALE, 0, " -"4) as usize,\n" -" scale(compass_reading.y, -COMPASS_SCALE, COMPASS_SCALE, 0, " -"4) as usize,\n" -" ),\n" -" Mode::Accelerometer => (\n" -" scale(\n" -" accelerometer_reading.x,\n" -" -ACCELEROMETER_SCALE,\n" -" ACCELEROMETER_SCALE,\n" -" 0,\n" -" 4,\n" -" ) as usize,\n" -" scale(\n" -" -accelerometer_reading.y,\n" -" -ACCELEROMETER_SCALE,\n" -" ACCELEROMETER_SCALE,\n" -" 0,\n" -" 4,\n" -" ) as usize,\n" -" ),\n" -" };\n" -" image[y][x] = 255;\n" -" display.show(&mut timer, image, 100);\n" -"\n" -" // If button A is pressed, switch to the next mode and briefly blink " -"all LEDs on.\n" -" if board.buttons.button_a.is_low().unwrap() {\n" -" if !button_pressed {\n" -" mode = mode.next();\n" -" display.show(&mut timer, [[255; 5]; 5], 200);\n" -" }\n" -" button_pressed = true;\n" -" } else {\n" -" button_pressed = false;\n" -" }\n" -" }\n" -"}\n" -"\n" -"#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n" -"enum Mode {\n" -" Compass,\n" -" Accelerometer,\n" -"}\n" -"\n" -"impl Mode {\n" -" fn next(self) -> Self {\n" -" match self {\n" -" Self::Compass => Self::Accelerometer,\n" -" Self::Accelerometer => Self::Compass,\n" -" }\n" -" }\n" -"}\n" -"\n" -"fn scale(value: i32, min_in: i32, max_in: i32, min_out: i32, max_out: i32) -" -"> i32 {\n" -" let range_in = max_in - min_in;\n" -" let range_out = max_out - min_out;\n" -" cap(\n" -" min_out + range_out * (value - min_in) / range_in,\n" -" min_out,\n" -" max_out,\n" -" )\n" -"}\n" -"\n" -"fn cap(value: i32, min_value: i32, max_value: i32) -> i32 {\n" -" max(min_value, min(value, max_value))\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/solutions-afternoon.md:5 -msgid "([back to exercise](rtc.md))" -msgstr "([返回練習](rtc.md))" - -#: src/exercises/bare-metal/solutions-afternoon.md:7 -msgid "`main.rs`:" -msgstr "`main.rs`:" - -#: src/exercises/bare-metal/solutions-afternoon.md:9 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: top\n" -"#![no_main]\n" -"#![no_std]\n" -"\n" -"mod exceptions;\n" -"mod logger;\n" -"mod pl011;\n" -"// ANCHOR_END: top\n" -"mod pl031;\n" -"\n" -"use crate::pl031::Rtc;\n" -"use arm_gic::gicv3::{IntId, Trigger};\n" -"use arm_gic::{irq_enable, wfi};\n" -"use chrono::{TimeZone, Utc};\n" -"use core::hint::spin_loop;\n" -"// ANCHOR: imports\n" -"use crate::pl011::Uart;\n" -"use arm_gic::gicv3::GicV3;\n" -"use core::panic::PanicInfo;\n" -"use log::{error, info, trace, LevelFilter};\n" -"use smccc::psci::system_off;\n" -"use smccc::Hvc;\n" -"\n" -"/// Base addresses of the GICv3.\n" -"const GICD_BASE_ADDRESS: *mut u64 = 0x800_0000 as _;\n" -"const GICR_BASE_ADDRESS: *mut u64 = 0x80A_0000 as _;\n" -"\n" -"/// Base address of the primary PL011 UART.\n" -"const PL011_BASE_ADDRESS: *mut u32 = 0x900_0000 as _;\n" -"// ANCHOR_END: imports\n" -"\n" -"/// Base address of the PL031 RTC.\n" -"const PL031_BASE_ADDRESS: *mut u32 = 0x901_0000 as _;\n" -"/// The IRQ used by the PL031 RTC.\n" -"const PL031_IRQ: IntId = IntId::spi(2);\n" -"\n" -"// ANCHOR: main\n" -"#[no_mangle]\n" -"extern \"C\" fn main(x0: u64, x1: u64, x2: u64, x3: u64) {\n" -" // Safe because `PL011_BASE_ADDRESS` is the base address of a PL011 " -"device,\n" -" // and nothing else accesses that address range.\n" -" let uart = unsafe { Uart::new(PL011_BASE_ADDRESS) };\n" -" logger::init(uart, LevelFilter::Trace).unwrap();\n" -"\n" -" info!(\"main({:#x}, {:#x}, {:#x}, {:#x})\", x0, x1, x2, x3);\n" -"\n" -" // Safe because `GICD_BASE_ADDRESS` and `GICR_BASE_ADDRESS` are the " -"base\n" -" // addresses of a GICv3 distributor and redistributor respectively, and\n" -" // nothing else accesses those address ranges.\n" -" let mut gic = unsafe { GicV3::new(GICD_BASE_ADDRESS, " -"GICR_BASE_ADDRESS) };\n" -" gic.setup();\n" -" // ANCHOR_END: main\n" -"\n" -" // Safe because `PL031_BASE_ADDRESS` is the base address of a PL031 " -"device,\n" -" // and nothing else accesses that address range.\n" -" let mut rtc = unsafe { Rtc::new(PL031_BASE_ADDRESS) };\n" -" let timestamp = rtc.read();\n" -" let time = Utc.timestamp_opt(timestamp.into(), 0).unwrap();\n" -" info!(\"RTC: {time}\");\n" -"\n" -" GicV3::set_priority_mask(0xff);\n" -" gic.set_interrupt_priority(PL031_IRQ, 0x80);\n" -" gic.set_trigger(PL031_IRQ, Trigger::Level);\n" -" irq_enable();\n" -" gic.enable_interrupt(PL031_IRQ, true);\n" -"\n" -" // Wait for 3 seconds, without interrupts.\n" -" let target = timestamp + 3;\n" -" rtc.set_match(target);\n" -" info!(\n" -" \"Waiting for {}\",\n" -" Utc.timestamp_opt(target.into(), 0).unwrap()\n" -" );\n" -" trace!(\n" -" \"matched={}, interrupt_pending={}\",\n" -" rtc.matched(),\n" -" rtc.interrupt_pending()\n" -" );\n" -" while !rtc.matched() {\n" -" spin_loop();\n" -" }\n" -" trace!(\n" -" \"matched={}, interrupt_pending={}\",\n" -" rtc.matched(),\n" -" rtc.interrupt_pending()\n" -" );\n" -" info!(\"Finished waiting\");\n" -"\n" -" // Wait another 3 seconds for an interrupt.\n" -" let target = timestamp + 6;\n" -" info!(\n" -" \"Waiting for {}\",\n" -" Utc.timestamp_opt(target.into(), 0).unwrap()\n" -" );\n" -" rtc.set_match(target);\n" -" rtc.clear_interrupt();\n" -" rtc.enable_interrupt(true);\n" -" trace!(\n" -" \"matched={}, interrupt_pending={}\",\n" -" rtc.matched(),\n" -" rtc.interrupt_pending()\n" -" );\n" -" while !rtc.interrupt_pending() {\n" -" wfi();\n" -" }\n" -" trace!(\n" -" \"matched={}, interrupt_pending={}\",\n" -" rtc.matched(),\n" -" rtc.interrupt_pending()\n" -" );\n" -" info!(\"Finished waiting\");\n" -"\n" -" // ANCHOR: main_end\n" -" system_off::().unwrap();\n" -"}\n" -"\n" -"#[panic_handler]\n" -"fn panic(info: &PanicInfo) -> ! {\n" -" error!(\"{info}\");\n" -" system_off::().unwrap();\n" -" loop {}\n" -"}\n" -"// ANCHOR_END: main_end\n" -"```" -msgstr "" - -#: src/exercises/bare-metal/solutions-afternoon.md:149 -msgid "`pl031.rs`:" -msgstr "`pl031.rs`:" - -#: src/exercises/bare-metal/solutions-afternoon.md:151 -msgid "" -"```rust\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"use core::ptr::{addr_of, addr_of_mut};\n" -"\n" -"#[repr(C, align(4))]\n" -"struct Registers {\n" -" /// Data register\n" -" dr: u32,\n" -" /// Match register\n" -" mr: u32,\n" -" /// Load register\n" -" lr: u32,\n" -" /// Control register\n" -" cr: u8,\n" -" _reserved0: [u8; 3],\n" -" /// Interrupt Mask Set or Clear register\n" -" imsc: u8,\n" -" _reserved1: [u8; 3],\n" -" /// Raw Interrupt Status\n" -" ris: u8,\n" -" _reserved2: [u8; 3],\n" -" /// Masked Interrupt Status\n" -" mis: u8,\n" -" _reserved3: [u8; 3],\n" -" /// Interrupt Clear Register\n" -" icr: u8,\n" -" _reserved4: [u8; 3],\n" -"}\n" -"\n" -"/// Driver for a PL031 real-time clock.\n" -"#[derive(Debug)]\n" -"pub struct Rtc {\n" -" registers: *mut Registers,\n" -"}\n" -"\n" -"impl Rtc {\n" -" /// Constructs a new instance of the RTC driver for a PL031 device at " -"the\n" -" /// given base address.\n" -" ///\n" -" /// # Safety\n" -" ///\n" -" /// The given base address must point to the MMIO control registers of " -"a\n" -" /// PL031 device, which must be mapped into the address space of the " -"process\n" -" /// as device memory and not have any other aliases.\n" -" pub unsafe fn new(base_address: *mut u32) -> Self {\n" -" Self {\n" -" registers: base_address as *mut Registers,\n" -" }\n" -" }\n" -"\n" -" /// Reads the current RTC value.\n" -" pub fn read(&self) -> u32 {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL031 device which is appropriately mapped.\n" -" unsafe { addr_of!((*self.registers).dr).read_volatile() }\n" -" }\n" -"\n" -" /// Writes a match value. When the RTC value matches this then an " -"interrupt\n" -" /// will be generated (if it is enabled).\n" -" pub fn set_match(&mut self, value: u32) {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL031 device which is appropriately mapped.\n" -" unsafe { addr_of_mut!((*self.registers).mr).write_volatile(value) }\n" -" }\n" -"\n" -" /// Returns whether the match register matches the RTC value, whether or " -"not\n" -" /// the interrupt is enabled.\n" -" pub fn matched(&self) -> bool {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL031 device which is appropriately mapped.\n" -" let ris = unsafe { addr_of!((*self.registers).ris)." -"read_volatile() };\n" -" (ris & 0x01) != 0\n" -" }\n" -"\n" -" /// Returns whether there is currently an interrupt pending.\n" -" ///\n" -" /// This should be true iff `matched` returns true and the interrupt is\n" -" /// masked.\n" -" pub fn interrupt_pending(&self) -> bool {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL031 device which is appropriately mapped.\n" -" let ris = unsafe { addr_of!((*self.registers).mis)." -"read_volatile() };\n" -" (ris & 0x01) != 0\n" -" }\n" -"\n" -" /// Sets or clears the interrupt mask.\n" -" ///\n" -" /// When the mask is true the interrupt is enabled; when it is false " -"the\n" -" /// interrupt is disabled.\n" -" pub fn enable_interrupt(&mut self, mask: bool) {\n" -" let imsc = if mask { 0x01 } else { 0x00 };\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL031 device which is appropriately mapped.\n" -" unsafe { addr_of_mut!((*self.registers).imsc)." -"write_volatile(imsc) }\n" -" }\n" -"\n" -" /// Clears a pending interrupt, if any.\n" -" pub fn clear_interrupt(&mut self) {\n" -" // Safe because we know that self.registers points to the control\n" -" // registers of a PL031 device which is appropriately mapped.\n" -" unsafe { addr_of_mut!((*self.registers).icr).write_volatile(0x01) }\n" -" }\n" -"}\n" -"\n" -"// Safe because it just contains a pointer to device memory, which can be\n" -"// accessed from any context.\n" -"unsafe impl Send for Rtc {}\n" -"```" -msgstr "" - -#: src/exercises/concurrency/solutions-morning.md:1 -msgid "Concurrency Morning Exercise" -msgstr "並行:上午練習" - -#: src/exercises/concurrency/solutions-morning.md:5 -msgid "([back to exercise](dining-philosophers.md))" -msgstr "([返回練習](dining-philosophers.md))" - -#: src/exercises/concurrency/solutions-morning.md:7 -msgid "" -"```rust\n" -"// Copyright 2022 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: Philosopher\n" -"use std::sync::{mpsc, Arc, Mutex};\n" -"use std::thread;\n" -"use std::time::Duration;\n" -"\n" -"struct Fork;\n" -"\n" -"struct Philosopher {\n" -" name: String,\n" -" // ANCHOR_END: Philosopher\n" -" left_fork: Arc>,\n" -" right_fork: Arc>,\n" -" thoughts: mpsc::SyncSender,\n" -"}\n" -"\n" -"// ANCHOR: Philosopher-think\n" -"impl Philosopher {\n" -" fn think(&self) {\n" -" self.thoughts\n" -" .send(format!(\"Eureka! {} has a new idea!\", &self.name))\n" -" .unwrap();\n" -" }\n" -" // ANCHOR_END: Philosopher-think\n" -"\n" -" // ANCHOR: Philosopher-eat\n" -" fn eat(&self) {\n" -" // ANCHOR_END: Philosopher-eat\n" -" println!(\"{} is trying to eat\", &self.name);\n" -" let left = self.left_fork.lock().unwrap();\n" -" let right = self.right_fork.lock().unwrap();\n" -"\n" -" // ANCHOR: Philosopher-eat-end\n" -" println!(\"{} is eating...\", &self.name);\n" -" thread::sleep(Duration::from_millis(10));\n" -" }\n" -"}\n" -"\n" -"static PHILOSOPHERS: &[&str] =\n" -" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" -"\n" -"fn main() {\n" -" // ANCHOR_END: Philosopher-eat-end\n" -" let (tx, rx) = mpsc::sync_channel(10);\n" -"\n" -" let forks = (0..PHILOSOPHERS.len())\n" -" .map(|_| Arc::new(Mutex::new(Fork)))\n" -" .collect::>();\n" -"\n" -" for i in 0..forks.len() {\n" -" let tx = tx.clone();\n" -" let mut left_fork = forks[i].clone();\n" -" let mut right_fork = forks[(i + 1) % forks.len()].clone();\n" -"\n" -" // To avoid a deadlock, we have to break the symmetry\n" -" // somewhere. This will swap the forks without deinitializing\n" -" // either of them.\n" -" if i == forks.len() - 1 {\n" -" std::mem::swap(&mut left_fork, &mut right_fork);\n" -" }\n" -"\n" -" let philosopher = Philosopher {\n" -" name: PHILOSOPHERS[i].to_string(),\n" -" thoughts: tx,\n" -" left_fork,\n" -" right_fork,\n" -" };\n" -"\n" -" thread::spawn(move || {\n" -" for _ in 0..100 {\n" -" philosopher.eat();\n" -" philosopher.think();\n" -" }\n" -" });\n" -" }\n" -"\n" -" drop(tx);\n" -" for thought in rx {\n" -" println!(\"{thought}\");\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/concurrency/solutions-afternoon.md:1 -msgid "Concurrency Afternoon Exercise" -msgstr "並行:下午練習" - -#: src/exercises/concurrency/solutions-afternoon.md:5 -msgid "([back to exercise](dining-philosophers-async.md))" -msgstr "([返回練習](dining-philosophers-async.md))" - -#: src/exercises/concurrency/solutions-afternoon.md:7 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: Philosopher\n" -"use std::sync::Arc;\n" -"use tokio::time;\n" -"use tokio::sync::mpsc::{self, Sender};\n" -"use tokio::sync::Mutex;\n" -"\n" -"struct Fork;\n" -"\n" -"struct Philosopher {\n" -" name: String,\n" -" // ANCHOR_END: Philosopher\n" -" left_fork: Arc>,\n" -" right_fork: Arc>,\n" -" thoughts: Sender,\n" -"}\n" -"\n" -"// ANCHOR: Philosopher-think\n" -"impl Philosopher {\n" -" async fn think(&self) {\n" -" self.thoughts\n" -" .send(format!(\"Eureka! {} has a new idea!\", &self.name))." -"await\n" -" .unwrap();\n" -" }\n" -" // ANCHOR_END: Philosopher-think\n" -"\n" -" // ANCHOR: Philosopher-eat\n" -" async fn eat(&self) {\n" -" // Pick up forks...\n" -" // ANCHOR_END: Philosopher-eat\n" -" let _first_lock = self.left_fork.lock().await;\n" -" // Add a delay before picking the second fork to allow the " -"execution\n" -" // to transfer to another task\n" -" time::sleep(time::Duration::from_millis(1)).await;\n" -" let _second_lock = self.right_fork.lock().await;\n" -"\n" -" // ANCHOR: Philosopher-eat-body\n" -" println!(\"{} is eating...\", &self.name);\n" -" time::sleep(time::Duration::from_millis(5)).await;\n" -" // ANCHOR_END: Philosopher-eat-body\n" -"\n" -" // The locks are dropped here\n" -" // ANCHOR: Philosopher-eat-end\n" -" }\n" -"}\n" -"\n" -"static PHILOSOPHERS: &[&str] =\n" -" &[\"Socrates\", \"Plato\", \"Aristotle\", \"Thales\", \"Pythagoras\"];\n" -"\n" -"#[tokio::main]\n" -"async fn main() {\n" -" // ANCHOR_END: Philosopher-eat-end\n" -" // Create forks\n" -" let mut forks = vec![];\n" -" (0..PHILOSOPHERS.len()).for_each(|_| forks.push(Arc::new(Mutex::" -"new(Fork))));\n" -"\n" -" // Create philosophers\n" -" let (philosophers, mut rx) = {\n" -" let mut philosophers = vec![];\n" -" let (tx, rx) = mpsc::channel(10);\n" -" for (i, name) in PHILOSOPHERS.iter().enumerate() {\n" -" let left_fork = forks[i].clone();\n" -" let right_fork = forks[(i + 1) % PHILOSOPHERS.len()].clone();\n" -" philosophers.push(Philosopher {\n" -" name: name.to_string(),\n" -" left_fork: if i % 2 == 0 { left_fork.clone() } else " -"{ right_fork.clone() },\n" -" right_fork: if i % 2 == 0 { right_fork } else " -"{ left_fork },\n" -" thoughts: tx.clone(),\n" -" });\n" -" }\n" -" (philosophers, rx)\n" -" // tx is dropped here, so we don't need to explicitly drop it later\n" -" };\n" -"\n" -" // Make them think and eat\n" -" for phil in philosophers {\n" -" tokio::spawn(async move {\n" -" for _ in 0..100 {\n" -" phil.think().await;\n" -" phil.eat().await;\n" -" }\n" -" });\n" -"\n" -" }\n" -"\n" -" // Output their thoughts\n" -" while let Some(thought) = rx.recv().await {\n" -" println!(\"Here is a thought: {thought}\");\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/exercises/concurrency/solutions-afternoon.md:121 -msgid "([back to exercise](chat-app.md))" -msgstr "([返回練習](chat-app.md))" - -#: src/exercises/concurrency/solutions-afternoon.md:119 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: setup\n" -"use futures_util::sink::SinkExt;\n" -"use std::error::Error;\n" -"use std::net::SocketAddr;\n" -"use tokio::net::{TcpListener, TcpStream};\n" -"use tokio::sync::broadcast::{channel, Sender};\n" -"use tokio_websockets::{Message, ServerBuilder, WebsocketStream};\n" -"// ANCHOR_END: setup\n" -"\n" -"// ANCHOR: handle_connection\n" -"async fn handle_connection(\n" -" addr: SocketAddr,\n" -" mut ws_stream: WebsocketStream,\n" -" bcast_tx: Sender,\n" -") -> Result<(), Box> {\n" -" // ANCHOR_END: handle_connection\n" -"\n" -" ws_stream\n" -" .send(Message::text(\"Welcome to chat! Type a message\".into()))\n" -" .await?;\n" -" let mut bcast_rx = bcast_tx.subscribe();\n" -"\n" -" // A continuous loop for concurrently performing two tasks: (1) " -"receiving\n" -" // messages from `ws_stream` and broadcasting them, and (2) receiving\n" -" // messages on `bcast_rx` and sending them to the client.\n" -" loop {\n" -" tokio::select! {\n" -" incoming = ws_stream.next() => {\n" -" match incoming {\n" -" Some(Ok(msg)) => {\n" -" let msg = msg.as_text()?;\n" -" println!(\"From client {addr:?} {msg:?}\");\n" -" bcast_tx.send(msg.into())?;\n" -" }\n" -" Some(Err(err)) => return Err(err.into()),\n" -" None => return Ok(()),\n" -" }\n" -" }\n" -" msg = bcast_rx.recv() => {\n" -" ws_stream.send(Message::text(msg?)).await?;\n" -" }\n" -" }\n" -" }\n" -" // ANCHOR: main\n" -"}\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> Result<(), Box> {\n" -" let (bcast_tx, _) = channel(16);\n" -"\n" -" let listener = TcpListener::bind(\"127.0.0.1:2000\").await?;\n" -" println!(\"listening on port 2000\");\n" -"\n" -" loop {\n" -" let (socket, addr) = listener.accept().await?;\n" -" println!(\"New connection from {addr:?}\");\n" -" let bcast_tx = bcast_tx.clone();\n" -" tokio::spawn(async move {\n" -" // Wrap the raw TCP stream into a websocket.\n" -" let ws_stream = ServerBuilder::new().accept(socket).await?;\n" -"\n" -" handle_connection(addr, ws_stream, bcast_tx).await\n" -" });\n" -" }\n" -"}\n" -"// ANCHOR_END: main\n" -"```" -msgstr "" - -#: src/exercises/concurrency/solutions-afternoon.md:204 -msgid "" -"```rust,compile_fail\n" -"// Copyright 2023 Google LLC\n" -"//\n" -"// Licensed under the Apache License, Version 2.0 (the \"License\");\n" -"// you may not use this file except in compliance with the License.\n" -"// You may obtain a copy of the License at\n" -"//\n" -"// http://www.apache.org/licenses/LICENSE-2.0\n" -"//\n" -"// Unless required by applicable law or agreed to in writing, software\n" -"// distributed under the License is distributed on an \"AS IS\" BASIS,\n" -"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" -"// See the License for the specific language governing permissions and\n" -"// limitations under the License.\n" -"\n" -"// ANCHOR: setup\n" -"use futures_util::SinkExt;\n" -"use http::Uri;\n" -"use tokio::io::{AsyncBufReadExt, BufReader};\n" -"use tokio_websockets::{ClientBuilder, Message};\n" -"\n" -"#[tokio::main]\n" -"async fn main() -> Result<(), tokio_websockets::Error> {\n" -" let mut ws_stream = ClientBuilder::from_uri(Uri::" -"from_static(\"ws://127.0.0.1:2000\"))\n" -" .connect()\n" -" .await?;\n" -"\n" -" let stdin = tokio::io::stdin();\n" -" let mut stdin = BufReader::new(stdin);\n" -"\n" -" // ANCHOR_END: setup\n" -" // Continuous loop for concurrently sending and receiving messages.\n" -" loop {\n" -" let mut line = String::new();\n" -" tokio::select! {\n" -" incoming = ws_stream.next() => {\n" -" match incoming {\n" -" Some(Ok(msg)) => println!(\"From server: {}\", msg." -"as_text()?),\n" -" Some(Err(err)) => return Err(err.into()),\n" -" None => return Ok(()),\n" -" }\n" -" }\n" -" res = stdin.read_line(&mut line) => {\n" -" match res {\n" -" Ok(0) => return Ok(()),\n" -" Ok(_) => ws_stream.send(Message::text(line.trim_end()." -"to_string())).await?,\n" -" Err(err) => return Err(err.into()),\n" -" }\n" -" }\n" -"\n" -" }\n" -" }\n" -"}\n" -"```" -msgstr "" - -#: src/structs/tuple-structs.md:42 -msgid "Operator overloading is discussed on Day 3 (generics)." -msgstr "運算子超載會在第 3 天 (泛型) 討論。" - -#: src/structs/tuple-structs.md:43 -msgid "" -"The example is a subtle reference to the [Mars Climate Orbiter](https://en." -"wikipedia.org/wiki/Mars_Climate_Orbiter) failure." -msgstr "" -"此範例巧妙地以 [Mars Climate Orbiter](https://en.wikipedia.org/wiki/" -"Mars_Climate_Orbiter) 的失敗經驗做為參照。" - -#: src/traits/closures.md:34 -msgid "" -"An `Fn` (e.g. `add_3`) neither consumes nor mutates captured values, or " -"perhaps captures nothing at all. It can be called multiple times " -"concurrently." -msgstr "" -"`Fn` (例如 `add_3`) 既不會耗用也不會修改擷取的值,或許 也可說是不會擷取任何" -"值,因此可以多次並行呼叫。" - -#: src/traits/closures.md:37 -msgid "" -"An `FnMut` (e.g. `accumulate`) might mutate captured values. You can call it " -"multiple times, but not concurrently." -msgstr "" -"`FnMut` (例如 `accumulate`) 可能會修改擷取的值,因此可以多次呼叫 (但不得並行" -"呼叫)。" - -#: src/traits/closures.md:40 -msgid "" -"If you have an `FnOnce` (e.g. `multiply_sum`), you may only call it once. It " -"might consume captured values." -msgstr "" -"如果是 `FnOnce` (例如`multiply_sum`),也許就只能呼叫一次,因為這可能會耗用 擷" -"取的值。" - -#: src/traits/closures.md:47 -msgid "" -"The compiler also infers `Copy` (e.g. for `add_3`) and `Clone` (e.g. " -"`multiply_sum`), depending on what the closure captures." -msgstr "" -"編譯器也會根據閉包擷取到的內容來推論 `Copy` (例如針對 `add_3`) 和 `Clone` (例" -"如 `multiply_sum`)." - -#: src/traits/closures.md:50 -msgid "" -"By default, closures will capture by reference if they can. The `move` " -"keyword makes them capture by value." -msgstr "" -"根據預設,閉包會依據參照來擷取內容 (如果可行的話)。`move` 關鍵字則可讓閉包根" -"據值 來擷取內容。" - -#: src/SUMMARY.md:73 -msgid "Pattern Matching (TBD)" -msgstr "模式配對 (未定)" - -#: src/SUMMARY.md:120 -msgid "Cell/RefCell" -msgstr "Cell/RefCell" - -#: src/SUMMARY.md:238 src/bare-metal/aps/entry-point.md:1 -msgid "Getting Ready to Rust" -msgstr "準備使用 Rust" - -#: src/SUMMARY.md:250 src/bare-metal/aps/exceptions.md:1 -msgid "Exceptions" -msgstr "例外狀況" - -#: src/index.md:3 -msgid "" -"[![Build workflow](https://img.shields.io/github/actions/workflow/status/" -"google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" -"google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain) [!" -"[GitHub contributors](https://img.shields.io/github/contributors/google/" -"comprehensive-rust?style=flat-square)](https://github.com/google/" -"comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields." -"io/github/stars/google/comprehensive-rust?style=flat-square)](https://github." -"com/google/comprehensive-rust/stargazers)" -msgstr "" -"[![Build workflow](https://img.shields.io/github/actions/workflow/status/" -"google/comprehensive-rust/build.yml?style=flat-square)](https://github.com/" -"google/comprehensive-rust/actions/workflows/build.yml?query=branch%3Amain) [!" -"[GitHub contributors](https://img.shields.io/github/contributors/google/" -"comprehensive-rust?style=flat-square)](https://github.com/google/" -"comprehensive-rust/graphs/contributors) [![GitHub stars](https://img.shields." -"io/github/stars/google/comprehensive-rust?style=flat-square)](https://github." -"com/google/comprehensive-rust/stargazers)" - -#: src/index.md:7 -msgid "" -"This is a free Rust course developed by the Android team at Google. The " -"course covers the full spectrum of Rust, from basic syntax to advanced " -"topics like generics and error handling." -msgstr "" -"這個免費的 Rust 課程是由 Google 的 Android 團隊負責開發。本課程涵蓋 Rust 的全" -"部內容,從基礎語法到進階主題 (泛型和錯誤處理等),應有盡有。" - -#: src/index.md:11 -msgid "" -"The latest version of the course can be found at . If you are reading somewhere else, please check there " -"for updates." -msgstr "" -"如需最新版課程,請造訪 。假如您" -"是在其他網址閱讀課程資料,別忘了查看這個連結的內容是否有更新。" - -#: src/index.md:22 -msgid "We call the first three course days Rust Fundamentals." -msgstr "我們將前三天的課程稱為「Rust 基礎知識」。" - -#: src/index.md:24 -msgid "" -"Building on this, you're invited to dive into one or more specialized topics:" -msgstr "在此基礎上,我們將誠摯邀請您深入探討一或多個專題:" - -#: src/index.md:31 -msgid "" -"[Concurrency](concurrency.md): a whole-day class on concurrency in Rust. We " -"cover both classical concurrency (preemptively scheduling using threads and " -"mutexes) and async/await concurrency (cooperative multitasking using " -"futures)." -msgstr "" -"[並行](concurrency.md):這個全天課程著重於 Rust 中的並行問題。我們將探討傳統" -"並行 (使用執行緒和互斥鎖進行先占式排程) 以及 async/await 並行 (使用 future 進" -"行合作多工處理)。" - -#: src/index.md:48 -msgid "" -"The course assumes that you already know how to program. Rust is a " -"statically-typed language and we will sometimes make comparisons with C and " -"C++ to better explain or contrast the Rust approach." -msgstr "" -"本課程假設您已瞭解如何設計程式。Rust 是一種靜態的程式設計類型,我們有時會將其" -"與 C 和 C++ 比較,以便進一步解釋或凸顯 Rust 做法上的差別。" - -#: src/index.md:52 -msgid "" -"If you know how to program in a dynamically-typed language such as Python or " -"JavaScript, then you will be able to follow along just fine too." -msgstr "" -"如果您知道如何以 Python 或 JavaScript 等動態程式語言編寫程式,也很適合跟著我" -"們學習 Rust。" - -#: src/running-the-course.md:8 -msgid "" -"We typically run classes from 10:00 am to 4:00 pm, with a 1 hour lunch break " -"in the middle. This leaves 2.5 hours for the morning class and 2.5 hours for " -"the afternoon class. Note that this is just a recommendation: you can also " -"spend 3 hour on the morning session to give people more time for exercises. " -"The downside of longer session is that people can become very tired after 6 " -"full hours of class in the afternoon." -msgstr "" -"我們一般會從上午 10 點上課到下午 4 點,中間 1 小時午休。也就是說,上下午課程" -"各為 2.5 小時。請注意,這只是建議的上課時間:您也可以將上午的課程訂為 3 小" -"時,讓學員有更多時間練習。延長課程時間的缺點是,學員上了整整 6 小時的課,到了" -"下午可能會非常疲倦。" - -#: src/running-the-course/course-structure.md:5 -msgid "Rust Fundamentals" -msgstr "Rust 基礎知識" - -#: src/running-the-course/course-structure.md:7 -msgid "" -"The first three days make up [Rust Fundaments](../welcome-day-1.md). The " -"days are fast paced and we cover a lot of ground:" -msgstr "" -"我們會在前三天介紹 [Rust 基礎知識](../welcome-day-1.md)。這幾天的步調會稍快," -"因為要探討許多層面:" - -#: src/running-the-course/course-structure.md:10 -msgid "Day 1: Basic Rust, syntax, control flow, creating and consuming values." -msgstr "第 1 天:Rust 基本概念、語法、控制流程、建立及取用值。" - -#: src/cargo.md:10 -msgid "**Please follow the instructions on .**" -msgstr "**請按照 中的指示操作。**" - -#: src/cargo/rust-ecosystem.md:32 -msgid "" -"Dependencies can also be resolved from alternative [registries](https://doc." -"rust-lang.org/cargo/reference/registries.html), git, folders, and more." -msgstr "" -"您也可以透過其他[註冊資料庫](https://doc.rust-lang.org/cargo/reference/" -"registries.html)、git、資料夾等管道解析依附元件。" - -#: src/cargo/running-locally.md:15 -msgid "" -"You can use any later version too since Rust maintains backwards " -"compatibility." -msgstr "由於 Rust 保有回溯相容性,您也可以使用任何後續版本。" - -#: src/welcome-day-1.md:3 -msgid "" -"This is the first day of Rust Fundamentals. We will cover a lot of ground " -"today:" -msgstr "今天是學習 Rust 基礎知識的第一天,我們會探討許多內容:" - -#: src/welcome-day-1/what-is-rust.md:25 -msgid "" -"Can be scaled down to very constrained devices such as microcontrollers." -msgstr "可縮減到十分受限的裝置規模,例如微控制器。" - -#: src/hello-world.md:22 -msgid "" -"This slide tries to make the students comfortable with Rust code. They will " -"see a ton of it over the next three days so we start small with something " -"familiar." -msgstr "" -"我們會藉由這張投影片,試著讓學生熟悉 Rust 程式碼。在接下來的三天裡,他們會大" -"量接觸到這些內容,所以我們得從他們熟悉的小地方著手。" - -#: src/hello-world.md:27 -msgid "" -"Rust is very much like other languages in the C/C++/Java tradition. It is " -"imperative and it doesn't try to reinvent things unless absolutely necessary." -msgstr "" -"Rust 與 C/C++/Java 傳統中的其他語言非常相似。它是指令式的程式語言,除非絕對必" -"要,否則不會嘗試改編任何內容。" - -#: src/hello-world.md:40 -msgid "" -"Rust is multi-paradigm. For example, it has powerful [object-oriented " -"programming features](https://doc.rust-lang.org/book/ch17-00-oop.html), and, " -"while it is not a functional language, it includes a range of [functional " -"concepts](https://doc.rust-lang.org/book/ch13-00-functional-features.html)." -msgstr "" -"Rust 是多範式的語言。舉例來說,它具備強大的[物件導向程式設計功能](https://" -"doc.rust-lang.org/book/ch17-00-oop.html),雖然並非函式語言,卻涉及各式各樣的" -"[函式概念](https://doc.rust-lang.org/book/ch13-00-functional-features.html)。" - -#: src/hello-world/small-example.md:44 -msgid "" -"In a shell `rustup doc std::fmt` will open a browser on the local std::fmt " -"documentation" -msgstr "" -"在殼層中,`rustup doc std::fmt` 會開啟本機 std::fmt 說明文件上的瀏覽器。" - -#: src/why-rust/runtime.md:6 -msgid "Integer overflow is defined (panic or wrap-around)." -msgstr "整數溢位的行為是明確的 (恐慌或迴繞)。" - -#: src/why-rust/runtime.md:12 -msgid "" -"Integer overflow is defined via the [`overflow-checks`](https://doc.rust-" -"lang.org/rustc/codegen-options/index.html#overflow-checks) compile-time " -"flag. If enabled, the program will panic (a controlled crash of the " -"program), otherwise you get wrap-around semantics. By default, you get " -"panics in debug mode (`cargo build`) and wrap-around in release mode (`cargo " -"build --release`)." -msgstr "" -"整數溢位的處理是透過 [`overflow-checks`](https://doc.rust-lang.org/rustc/" -"codegen-options/index.html#overflow-checks) 編譯時間標記定義的。如果啟用的" -"話,程式就會恐慌 (程式受控地異常終止),如未啟用,則會發生語意迴繞現象。根據預" -"設,在偵錯模式 (`cargo build`) 中會發生恐慌,在發布模式 (`cargo build --" -"release`) 中會發生迴繞。" - -#: src/why-rust/modern.md:3 -msgid "Rust is built with all the experience gained in the last decades." -msgstr "Rust 是根據過去數十年累積的所有經驗打造而成。" - -#: src/basic-syntax/scalar-types.md:5 -msgid "`-10`, `0`, `1_000`, `123_i64`" -msgstr "`-10`、`0`、`1_000`、`123_i64`" - -#: src/basic-syntax/scalar-types.md:6 -msgid "`0`, `123`, `10_u16`" -msgstr "`0`、`123`、`10_u16`" - -#: src/basic-syntax/scalar-types.md:7 -msgid "`3.14`, `-10.0e20`, `2_f32`" -msgstr "`3.14`、`-10.0e20`、`2_f32`" - -#: src/basic-syntax/scalar-types.md:16 -msgid "`char` is 32 bits wide," -msgstr "`char` 寬度為 32 位元" - -#: src/basic-syntax/scalar-types.md:17 -msgid "`bool` is 8 bits wide." -msgstr "`bool` 寬度為 8 位元" - -#: src/basic-syntax/scalar-types.md:43 -msgid "" -"All underscores in numbers can be left out, they are for legibility only. So " -"`1_000` can be written as `1000` (or `10_00`), and `123_i64` can be written " -"as `123i64`." -msgstr "" -"數字中的底線全都可以省略,寫出來只是為了方便閱讀。換句話說,`1_000` 可以寫成 " -"`1000` (或 `10_00`),而 `123_i64` 則可寫成 `123i64`。" - -#: src/basic-syntax/compound-types.md:34 -msgid "" -"A value of the array type `[T; N]` holds `N` (a compile-time constant) " -"elements of the same type `T`. Note that the length of the array is _part of " -"its type_, which means that `[u8; 3]` and `[u8; 4]` are considered two " -"different types." -msgstr "" -"陣列型別 `[T; N]` 的值會保留同樣屬於 `T` 型別的 `N` (編譯時間常數) 元素。請注" -"意,陣列的長度是「其型別的一部分」,也就是說 `[u8; 3]` 和 `[u8; 4]` 視為兩種" -"不同型別。" - -#: src/basic-syntax/slices.md:17 -msgid "Question: What happens if you modify `a[3]` right before printing `s`?" -msgstr "問題:如果在輸出 `s` 前修改 `a[3]`,會有什麼影響?" - -#: src/basic-syntax/slices.md:33 -msgid "" -"The question about modifying `a[3]` can spark an interesting discussion, but " -"the answer is that for memory safety reasons you cannot do it through `a` at " -"this point in the execution, but you can read the data from both `a` and `s` " -"safely. It works before you created the slice, and again after the " -"`println`, when the slice is no longer used. More details will be explained " -"in the borrow checker section." -msgstr "" -"有關修改 `a[3]` 的問題可能引發有趣的討論,但正解是,基於記憶體安全因素,您無" -"法在執行作業的這個時間點,透過 `a` 修改 `a[3]`,但可以放心從 `a` 和 `s` 讀取" -"資料。此項目會在您建立切片前運作,並在 `println` 之後,也就是切片不再使用時再" -"次運作。更多細節會在借用檢查器的章節說明。" - -#: src/basic-syntax/rustdoc.md:33 -msgid "" -"Rustdoc comments can contain code snippets that we can run and test using " -"`cargo test`. We will discuss these tests in the [Testing section](../" -"testing/doc-tests.html)." -msgstr "" -"Rustdoc 註解可包含能使用 `cargo test` 執行及測試的程式碼片段。我們會在[「測" -"試」一節](../testing/doc-tests.html)討論這些測試。" - -#: src/basic-syntax/methods.md:34 -msgid "Add a static method called `Rectangle::new` and call this from `main`:" -msgstr "新增名為 `Rectangle::new` 的靜態方法,然後從 `main` 呼叫此方法:" - -#: src/basic-syntax/methods.md:42 -msgid "" -"While _technically_, Rust does not have custom constructors, static methods " -"are commonly used to initialize structs (but don't have to). The actual " -"constructor, `Rectangle { width, height }`, could be called directly. See " -"the [Rustnomicon](https://doc.rust-lang.org/nomicon/constructors.html)." -msgstr "" -"雖然「技術上」來說,Rust 沒有自訂的建構函式,但靜態方法經常用來初始化結構體 " -"(儘管並非必須)。因此,您可直接呼叫實際的建構函式 `Rectangle { width, height }" -"`。詳情請參閱 [Rustnomicon](https://doc.rust-lang.org/nomicon/constructors." -"html)。" - -#: src/basic-syntax/methods.md:45 -msgid "" -"Add a `Rectangle::square(width: u32)` constructor to illustrate that such " -"static methods can take arbitrary parameters." -msgstr "" -"新增 `Rectangle::square(width: u32)` 建構函式,說明這類靜態方法可以採用任意參" -"數。" - -#: src/exercises/day-1/morning.md:22 src/exercises/day-2/morning.md:11 -#: src/exercises/day-3/morning.md:9 src/exercises/bare-metal/morning.md:7 -#: src/exercises/concurrency/morning.md:12 -msgid "" -"After looking at the exercises, you can look at the [solutions](solutions-" -"morning.md) provided." -msgstr "完成練習後,您可以看看我們提供的[解決方案](solutions-morning.md)。" - -#: src/exercises/day-1/for-loops.md:95 -msgid "" -"The use of the reference `&array` within `for n in &array` is a subtle " -"preview of issues of ownership that will come later in the afternoon." -msgstr "" -"在 `for n in &array` 內使用 `&array` 參照項目是一個巧妙方式,可稍微預示下午將" -"談到的擁有權問題。" - -#: src/exercises/day-1/for-loops.md:98 -msgid "Without the `&`..." -msgstr "沒有 `&` 的影響..." - -#: src/exercises/day-1/for-loops.md:99 -msgid "" -"The loop would have been one that consumes the array. This is a change " -"[introduced in the 2021 Edition](https://doc.rust-lang.org/edition-guide/" -"rust-2021/IntoIterator-for-arrays.html)." -msgstr "" -"迴圈會是取用陣列的迴圈。這是 [2021 年版導入](https://doc.rust-lang.org/" -"edition-guide/rust-2021/IntoIterator-for-arrays.html)的變更。" - -#: src/exercises/day-1/for-loops.md:102 -msgid "" -"An implicit array copy would have occurred. Since `i32` is a copy type, " -"then `[i32; 3]` is also a copy type." -msgstr "" -"會發生隱含陣列複製的情形。由於 `i32` 是複製型別,因此 `[i32; 3]` 也會是複製型" -"別。" - -#: src/basic-syntax/static-and-const.md:3 -msgid "" -"Static and constant variables are two different ways to create globally-" -"scoped values that cannot be moved or reallocated during the execution of " -"the program. " -msgstr "" -"靜態和常數變數是建立全域範圍值的兩種不同方式,這個值無法在程式執行期間移動或" -"重新分配。" - -#: src/basic-syntax/static-and-const.md:8 -msgid "" -"Constant variables are evaluated at compile time and their values are " -"inlined wherever they are used:" -msgstr "常數變數會在編譯期間評估,且無論用於何處,其值都會內嵌:" - -#: src/basic-syntax/static-and-const.md:31 -msgid "" -"Only functions marked `const` can be called at compile time to generate " -"`const` values. `const` functions can however be called at runtime." -msgstr "" -"您只能在編譯期間呼叫標示為 `const` 的函式,以便產生 `const` 值,但可以在執行" -"階段呼叫 `const` 函式。" - -#: src/basic-syntax/static-and-const.md:35 -msgid "" -"Static variables will live during the whole execution of the program, and " -"therefore will not move:" -msgstr "靜態變數會在程式的整個執行過程中持續運作,因此不會移動:" - -#: src/basic-syntax/static-and-const.md:45 -msgid "" -"As noted in the [Rust RFC Book](https://rust-lang.github.io/rfcs/0246-const-" -"vs-static.html), these are not inlined upon use and have an actual " -"associated memory location. This is useful for unsafe and embedded code, " -"and the variable lives through the entirety of the program execution. When a " -"globally-scoped value does not have a reason to need object identity, " -"`const` is generally preferred." -msgstr "" -"如《[Rust RFC 手冊](https://rust-lang.github.io/rfcs/0246-const-vs-static." -"html)》所述,這類值在使用時不會內嵌,且具備實際相關聯的記憶體位置。這對不安全" -"和嵌入的程式碼很有幫助,且變數在程式執行全程都會持續運作。當全域範圍值沒有需" -"要物件識別子的理由時,通常首選會是使用 `const`。" - -#: src/basic-syntax/static-and-const.md:49 -msgid "" -"Because `static` variables are accessible from any thread, they must be " -"`Sync`. Interior mutability is possible through a [`Mutex`](https://doc.rust-" -"lang.org/std/sync/struct.Mutex.html), atomic or similar. It is also possible " -"to have mutable statics, but they require manual synchronisation so any " -"access to them requires `unsafe` code. We will look at [mutable statics](../" -"unsafe/mutable-static-variables.md) in the chapter on Unsafe Rust." -msgstr "" -"由於 `static` 變數可從任何執行緒存取,因此必須是 `Sync`。內部可變動性則可透過" -"原子或類似的 [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) " -"實現。也可能有可變動的靜態項目,但這些需要手動同步,因此每當存取這類項目時就" -"需要動用 `unsafe` 程式碼。我們會在「不安全的 Rust」章節中探討[可變動的靜態項" -"目](../unsafe/mutable-static-variables.md)。" - -#: src/basic-syntax/static-and-const.md:59 -msgid "" -"`static` provides object identity: an address in memory and state as " -"required by types with interior mutability such as `Mutex`." -msgstr "" -"`static` 提供物件識別子,也就是記憶體中的位址,和具有內部可變動性型別 (例如 " -"`Mutex`) 所需的狀態。" - -#: src/basic-syntax/static-and-const.md:61 -msgid "`thread_local` data can be created with the macro `std::thread_local`." -msgstr "您可以使用 `std::thread_local` 巨集來建立 `thread_local` 資料。" - -#: src/basic-syntax/static-and-const.md:63 -msgid "Properties table:" -msgstr "屬性表:" - -#: src/basic-syntax/static-and-const.md:65 -msgid "Property" -msgstr "資源" - -#: src/basic-syntax/static-and-const.md:65 -msgid "Static" -msgstr "靜態" - -#: src/basic-syntax/static-and-const.md:65 -msgid "Constant" -msgstr "常數" - -#: src/basic-syntax/static-and-const.md:67 -msgid "Has an address in memory" -msgstr "具備記憶體中的位址" - -#: src/basic-syntax/static-and-const.md:67 -#: src/basic-syntax/static-and-const.md:68 -#: src/basic-syntax/static-and-const.md:70 -#: src/basic-syntax/static-and-const.md:71 -msgid "Yes" -msgstr "是" - -#: src/basic-syntax/static-and-const.md:67 -msgid "No (inlined)" -msgstr "否 (已內嵌)" - -#: src/basic-syntax/static-and-const.md:68 -msgid "Lives for the entire duration of the program" -msgstr "在整個程式執行期間持續存在" - -#: src/basic-syntax/static-and-const.md:68 -#: src/basic-syntax/static-and-const.md:69 -#: src/basic-syntax/static-and-const.md:71 -msgid "No" -msgstr "否" - -#: src/basic-syntax/static-and-const.md:69 -msgid "Can be mutable" -msgstr "可變動" - -#: src/basic-syntax/static-and-const.md:69 -msgid "Yes (unsafe)" -msgstr "是 (不安全)" - -#: src/basic-syntax/static-and-const.md:70 -msgid "Yes (initialised at compile time)" -msgstr "是 (已在編譯時初始化)" - -#: src/basic-syntax/static-and-const.md:71 -msgid "Inlined wherever it is used" -msgstr "無論在何處使用都會內嵌" - -#: src/control-flow/novel.md:3 -msgid "" -"Rust has a few control flow constructs which differ from other languages. " -"They are used for pattern matching:" -msgstr "Rust 的某些控制流程結構與其他程式語言不同。這些結構會用於模式配對:" - -#: src/exercises/day-1/afternoon.md:5 -msgid "The Luhn algorithm," -msgstr "盧恩演算法" - -#: src/exercises/day-1/afternoon.md:7 -msgid "An exercise on pattern matching." -msgstr "練習模式配對" - -#: src/exercises/day-1/afternoon.md:11 src/exercises/day-2/afternoon.md:7 -#: src/exercises/bare-metal/afternoon.md:7 -#: src/exercises/concurrency/afternoon.md:13 -msgid "" -"After looking at the exercises, you can look at the [solutions](solutions-" -"afternoon.md) provided." -msgstr "完成練習後,您可以看看我們提供的[解決方案](solutions-afternoon.md)。" - -#: src/exercises/day-1/luhn.md:9 -msgid "" -"Moving from **right to left**, double every second digit: for the number " -"`1234`, we double `3` and `1`. For the number `98765`, we double `6` and `8`." -msgstr "" -"從**右到左**,將偶數位的數字乘二。以數字 `1234` 為例,請將 `3` 和 `1` 乘二;" -"若為數字 `98765`,請將 `6` 和 `8` 乘二。" - -#: src/exercises/day-1/luhn.md:12 -msgid "" -"After doubling a digit, sum the digits if the result is greater than 9. So " -"doubling `7` becomes `14` which becomes `1 + 4 = 5`." -msgstr "" -"將數字乘二後,如果結果大於 9,請將每位數字相加。所以,`7` 乘二等於 `14`,那麼" -"也就是 `1 + 4 = 5`。" - -#: src/exercises/day-1/luhn.md:19 -msgid "" -"Copy the code below to and implement the " -"function." -msgstr "將下方程式碼複製到 ,並實作函式。" - -#: src/exercises/day-1/luhn.md:21 -msgid "" -"Try to solve the problem the \"simple\" way first, using `for` loops and " -"integers. Then, revisit the solution and try to implement it with iterators." -msgstr "" -"使用「for」迴圈和整數,先嘗試以「簡單」的方式解決問題。接著,重新查看解決方" -"案,試著使用疊代器實作。" - -#: src/memory-management/stack.md:1 -msgid "Stack and Heap Example" -msgstr "堆疊和堆積範例" - -#: src/ownership/move-semantics.md:23 -msgid "" -"It is only the ownership that moves. Whether any machine code is generated " -"to manipulate the data itself is a matter of optimization, and such copies " -"are aggressively optimized away." -msgstr "" -"只有擁有權才會轉移。是否產生任何機器碼來操控資料本身是一個最優化問題,而系統" -"會主動將這些副本最優化。" - -#: src/ownership/move-semantics.md:25 -msgid "" -"Simple values (such as integers) can be marked `Copy` (see later slides)." -msgstr "簡單的值 (例如整數) 可標示為 `Copy` (請參閱後續投影片)。" - -#: src/ownership/double-free-modern-cpp.md:57 -msgid "" -"C++ has made a slightly different choice than Rust. Because `=` copies data, " -"the string data has to be cloned. Otherwise we would get a double-free when " -"either string goes out of scope." -msgstr "" -"C++ 提供的選擇與 Rust 略有不同。由於 `=` 會複製資料,所以字串資料一定要完成複" -"製。否則,假如其中任一字串超出範圍,就會導致重複釋放的結果。" - -#: src/ownership/double-free-modern-cpp.md:61 -msgid "" -"C++ also has [`std::move`](https://en.cppreference.com/w/cpp/utility/move), " -"which is used to indicate when a value may be moved from. If the example had " -"been `s2 = std::move(s1)`, no heap allocation would take place. After the " -"move, `s1` would be in a valid but unspecified state. Unlike Rust, the " -"programmer is allowed to keep using `s1`." -msgstr "" -"C++ 也提供 [`std::move`](https://en.cppreference.com/w/cpp/utility/move),用" -"於指出何時可以轉移特定值。例如假設是 `s2 = std::move(s1)`,就不會發生堆積分配" -"的情形。轉移之後,`s1` 會處於有效但未指定的狀態。與 Rust 不同的是,程式設計師" -"可以繼續使用 `s1`。" - -#: src/ownership/double-free-modern-cpp.md:66 -msgid "" -"Unlike Rust, `=` in C++ can run arbitrary code as determined by the type " -"which is being copied or moved." -msgstr "" -"C++ 中的 `=` 可以依照要複製或轉移的型別來執行任何程式碼,這點與 Rust 不同。" - -#: src/methods.md:34 -msgid "Point out the use of the keyword `self`, a method receiver." -msgstr "指出我們會使用關鍵字 `self`,也就是方法接收器。" - -#: src/methods.md:35 -msgid "" -"Show that it is an abbreviated term for `self: Self` and perhaps show how " -"the struct name could also be used." -msgstr "說明 `self` 是 `self: Self` 的縮寫,或許也能示範結構體名稱的可能用法。" - -#: src/exercises/day-2/morning.md:5 -msgid "Storing books and querying the collection" -msgstr "儲存書籍並查詢館藏" - -#: src/exercises/day-2/morning.md:7 -msgid "Keeping track of health statistics for patients" -msgstr "追蹤病患的健康統計資料" - -#: src/exercises/day-2/book-library.md:18 -msgid "" -"Use this to model a library's book collection. Copy the code below to " -" and update the types to make it compile:" -msgstr "" -"這可用來建立圖書館的館藏模型。請將下列程式碼複製到 ,然後更新型別以利編譯:" - -#: src/std/hashmap.md:64 -msgid "" -"This type has several \"method-specific\" return types, such as `std::" -"collections::hash_map::Keys`. These types often appear in searches of the " -"Rust docs. Show students the docs for this type, and the helpful link back " -"to the `keys` method." -msgstr "" -"這個型別有多個「方法專屬」的傳回型別,例如 `std::collections::hash_map::" -"Keys`。這些型別經常會在 Rust 文件的搜尋結果中出現。請向學生展示這個型別的文" -"件,以及可返回 `keys` 方法的實用連結。" - -#: src/std/rc.md:18 -msgid "" -"See [`Arc`](../concurrency/shared_state/arc.md) and [`Mutex`](https://doc." -"rust-lang.org/std/sync/struct.Mutex.html) if you are in a multi-threaded " -"context." -msgstr "" -"如果您處於多執行緒的環境,請參閱 [`Arc`](../concurrency/shared_state/arc.md) " -"和 [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html)。" - -#: src/std/rc.md:30 -msgid "`Rc` in Rust is like `std::shared_ptr` in C++." -msgstr "Rust 中的 `Rc` 就像 C++ 中的 `std::shared_ptr` 一樣。" - -#: src/std/cell.md:1 -msgid "`Cell` and `RefCell`" -msgstr "`Cell` 和 `RefCell`" - -#: src/std/cell.md:8 -msgid "" -"`Cell` is typically used for simple types, as it requires copying or moving " -"values. More complex interior types typically use `RefCell`, which tracks " -"shared and exclusive references at runtime and panics if they are misused." -msgstr "" -"`Cell` 因為需要複製或移動值,通常用於簡單的型別。較複雜的內部型別通常會使用 " -"`RefCell`,可在執行階段和恐慌時追蹤共用和專屬的參照 (如果這些參照遭到濫用的" -"話)。" - -#: src/std/cell.md:47 -msgid "" -"If we were using `Cell` instead of `RefCell` in this example, we would have " -"to move the `Node` out of the `Rc` to push children, then move it back in. " -"This is safe because there's always one, un-referenced value in the cell, " -"but it's not ergonomic." -msgstr "" -"如果我們在本例中使用 `Cell` 而非 `RefCell`,可能須將 `Node` 移出 `Rc` 才能推" -"送子項,然後再將其移回。您可以放心執行這項操作,因為儲存格中始終有一個未參照" -"的值,但不符人體工學。" - -#: src/std/cell.md:48 -msgid "" -"To do anything with a Node, you must call a `RefCell` method, usually " -"`borrow` or `borrow_mut`." -msgstr "" -"如要對節點執行任何操作,您必須呼叫 `RefCell` 方法,通常是 `borrow` 或 " -"`borrow_mut`。" - -#: src/std/cell.md:49 -msgid "" -"Demonstrate that reference loops can be created by adding `root` to `subtree." -"children` (don't try to print it!)." -msgstr "" -"示範可以將 `root` 新增至 `subtree.children` (請勿嘗試輸出!) 來建立參照迴圈。" - -#: src/std/cell.md:50 -msgid "" -"To demonstrate a runtime panic, add a `fn inc(&mut self)` that increments " -"`self.value` and calls the same method on its children. This will panic in " -"the presence of the reference loop, with `thread 'main' panicked at 'already " -"borrowed: BorrowMutError'`." -msgstr "" -"如要演示執行階段發生的恐慌情形,請新增 `fn inc(&mut self)`,這可讓 `self." -"value` 遞增,並在其子項呼叫相同的方法。在有參照迴圈的情況下,這會引發恐慌,其" -"中的 `thread 'main' 會因 'already borrowed: BorrowMutError'` 而恐慌。" - -#: src/modules/filesystem.md:3 -msgid "" -"Omitting the module content will tell Rust to look for it in another file:" -msgstr "如果您省略模組內容,系統會指示 Rust 在其他檔案中尋找該內容:" - -#: src/modules/filesystem.md:9 -msgid "" -"This tells rust that the `garden` module content is found at `src/garden." -"rs`. Similarly, a `garden::vegetables` module can be found at `src/garden/" -"vegetables.rs`." -msgstr "" -"這會讓 Rust 知道 `garden` 模組內容是在 `src/garden.rs` 中找到的。同樣地," -"`garden::vegetables` 模組可在 `src/garden/vegetables.rs` 中找到。" - -#: src/modules/filesystem.md:37 -msgid "" -"Before Rust 2018, modules needed to be located at `module/mod.rs` instead of " -"`module.rs`, and this is still a working alternative for editions after 2018." -msgstr "" -"在 Rust 2018 之前,模組需位於 `module/mod.rs` 而非 `module.rs` 中,這仍然是 " -"2018 後續版本的可行替代方案。" - -#: src/modules/filesystem.md:39 -msgid "" -"The main reason to introduce `filename.rs` as alternative to `filename/mod." -"rs` was because many files named `mod.rs` can be hard to distinguish in IDEs." -msgstr "" -"導入 `filename.rs` 做為 `filename/mod.rs` 的替代方案,主要是因為許多名為 " -"`mod.rs` 的檔案在 IDE 中很難區分。" - -#: src/modules/filesystem.md:42 -msgid "Deeper nesting can use folders, even if the main module is a file:" -msgstr "更深層的巢狀結構可以使用資料夾,即使主要模組為檔案也一樣:" - -#: src/modules/filesystem.md:52 -msgid "" -"The place rust will look for modules can be changed with a compiler " -"directive:" -msgstr "Rust 尋找模組的位置可透過編譯器指令變更:" - -#: src/exercises/day-2/iterators-and-ownership.md:105 -msgid "" -"Experiment with the code above and then consult the documentation for [`impl " -"IntoIterator for &Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." -"html#impl-IntoIterator-for-%26'a+Vec%3CT,+A%3E) and [`impl IntoIterator for " -"Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-" -"for-Vec%3CT,+A%3E) to check your answers." -msgstr "" -"請用上方的程式碼進行試驗,並參閱 [`impl IntoIterator for &Vec`](https://" -"doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-" -"%26'a+Vec%3CT,+A%3E) 和 [`impl IntoIterator for Vec`](https://doc.rust-" -"lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-Vec%3CT,+A%3E) 的說明" -"文件確認答案。" - -#: src/traits/deriving-traits.md:3 -msgid "" -"Rust derive macros work by automatically generating code that implements the " -"specified traits for a data structure." -msgstr "Rust 衍生巨集的運作原理是自動產生程式碼,用於實作資料結構的指定特徵。" - -#: src/traits/default-methods.md:35 -msgid "Move method `not_equals` to a new trait `NotEquals`." -msgstr "將 `not_equals` 方法移至新特徵 `NotEquals`。" - -#: src/traits/default-methods.md:37 -msgid "Make `Equals` a super trait for `NotEquals`." -msgstr "將 `Equals` 設為 `NotEquals` 的超特徵。" - -#: src/traits/default-methods.md:46 -msgid "Provide a blanket implementation of `NotEquals` for `Equals`." -msgstr "為 `Equals` 提供 `NotEquals` 的大量實作。" - -#: src/traits/default-methods.md:58 -msgid "" -"With the blanket implementation, you no longer need `Equals` as a super " -"trait for `NotEqual`." -msgstr "採用大量實作後,您就不再需要使用 `Equals` 做為 `NotEqual` 的超特徵。" - -#: src/traits/default.md:46 -msgid "" -"the `..` syntax is called [struct update syntax](https://doc.rust-lang.org/" -"book/ch05-01-defining-structs.html#creating-instances-from-other-instances-" -"with-struct-update-syntax)" -msgstr "" -"`..` 語法稱為[結構體更新語法](https://doc.rust-lang.org/book/ch05-01-" -"defining-structs.html#creating-instances-from-other-instances-with-struct-" -"update-syntax)。" - -#: src/exercises/day-3/morning.md:3 -msgid "We will design a classical GUI library using traits and trait objects." -msgstr "我們將使用特徵和特徵物件設計一個典型的 GUI 程式庫。" - -#: src/exercises/day-3/morning.md:5 -msgid "" -"We will also look at enum dispatch with an exercise involving points and " -"polygons." -msgstr "我們也會透過點和多邊形的相關練習,探討列舉分派情形。" - -#: src/error-handling/try-operator.md:52 -msgid "" -"The return type of the function has to be compatible with the nested " -"functions it calls. For instance, a function returning a `Result` " -"can only apply the `?` operator on a function returning a `Result`. It cannot apply the `?` operator on a function returning an " -"`Option` or `Result` unless `OtherErr` implements " -"`From`. Reciprocally, a function returning an `Option` can only " -"apply the `?` operator on a function returning an `Option`." -msgstr "" -"函式的傳回型別必須與它呼叫的巢狀函式相容。舉例來說,傳回 `Result` 的" -"函式只能在傳回 `Result` 的函式上套用 `?` 運算子;無法在傳回 " -"`Option` 或 `Result` 的函式上套用該運算子,除非 " -"`OtherErr` 實作了 `From` 則例外。反之,傳回 `Option` 的函式只能在傳" -"回 `Option` 的函式上套用 `?` 運算子。" - -#: src/error-handling/try-operator.md:57 -msgid "" -"You can convert incompatible types into one another with the different " -"`Option` and `Result` methods such as `Option::ok_or`, `Result::ok`, " -"`Result::err`." -msgstr "" -"您可以使用不同的 `Option` 和 `Result` 方法,例如 `Option::ok_or`、`Result::" -"ok`、`Result::err` 等,將不相容的型別轉換為其他型別。" - -#: src/error-handling/converting-error-types-example.md:55 -msgid "" -"It is good practice for all error types that don't need to be `no_std` to " -"implement `std::error::Error`, which requires `Debug` and `Display`. The " -"`Error` crate for `core` is only available in [nightly](https://github.com/" -"rust-lang/rust/issues/103765), so not fully `no_std` compatible yet." -msgstr "" -"對所有不需要是 `no_std` 的錯誤型別來說,實作 `std::error::Error` 是很好的做" -"法,`std::error::Error` 會需要 `Debug` 和 `Display`。`core` 的 `Error` Crate " -"僅於 [nightly](https://github.com/rust-lang/rust/issues/103765) 提供,因此與 " -"`no_std` 尚未完全相容。" - -#: src/error-handling/converting-error-types-example.md:57 -msgid "" -"It's generally helpful for them to implement `Clone` and `Eq` too where " -"possible, to make life easier for tests and consumers of your library. In " -"this case we can't easily do so, because `io::Error` doesn't implement them." -msgstr "" -"對這種錯誤型別來說,在可能的情況下實作 `Clone` 和 `Eq` 通常也很有用,不僅有利" -"於程式庫的測試,使用者也會更輕鬆。但在本例中,我們無法輕易這麼做,因為 `io::" -"Error` 並未實作 `Clone` 和 `Eq`。" - -#: src/exercises/day-3/afternoon.md:5 -msgid "" -"For this exercise, we suggest using a local dev environment instead of the " -"Playground. This will allow you to run your binary on your own machine." -msgstr "" -"在這個練習中,建議您使用本機開發環境,不要用 Playground。這可讓您在自己的機器" -"上執行二進位檔。" - -#: src/exercises/day-3/afternoon.md:8 -msgid "" -"To get started, follow the [running locally](../../cargo/running-locally.md) " -"instructions." -msgstr "首先,請按照[在本機執行](../../cargo/running-locally.md)的說明操作。" - -#: src/exercises/day-1/solutions-afternoon.md:98 -msgid "Pattern matching" -msgstr "模式配對" - -#: src/exercises/day-1/solutions-afternoon.md:100 -msgid "TBD." -msgstr "未定。" - -#: src/exercises/concurrency/solutions-morning.md:104 -msgid "Link Checker" -msgstr "連結檢查器" - -#: src/exercises/concurrency/solutions-morning.md:106 -msgid "([back to exercise](link-checker.md))" -msgstr "([返回練習](link-checker.md))" +#~ msgid "Small Example" +#~ msgstr "簡短範例" + +#~ msgid "Why Rust?" +#~ msgstr "為什麼要使用 Rust?" + +#~ msgid "Compile Time Guarantees" +#~ msgstr "編譯時期保證" + +#~ msgid "Runtime Guarantees" +#~ msgstr "執行時期保證" + +#~ msgid "Modern Features" +#~ msgstr "新潮的功能" + +#~ msgid "Basic Syntax" +#~ msgstr "基本語法" + +#~ msgid "String vs str" +#~ msgstr "String 和 str" + +#~ msgid "Overloading" +#~ msgstr "超載" + +#~ msgid "Arrays and for Loops" +#~ msgstr "陣列和 for 迴圈" + +#~ msgid "Stack vs Heap" +#~ msgstr "堆疊和堆積" + +#~ msgid "Stack Memory" +#~ msgstr "堆疊記憶體" + +#~ msgid "Manual Memory Management" +#~ msgstr "手動記憶體管理" + +#~ msgid "Scope-Based Memory Management" +#~ msgstr "作用域式記憶體管理" + +#~ msgid "Garbage Collection" +#~ msgstr "垃圾回收" + +#~ msgid "Rust Memory Management" +#~ msgstr "Rust 記憶體管理" + +#~ msgid "Comparison" +#~ msgstr "比較" + +#~ msgid "Moved Strings in Rust" +#~ msgstr "Rust 中移動的字串" + +#~ msgid "Moves in Function Calls" +#~ msgstr "函式呼叫中的移動" + +#~ msgid "Copying and Cloning" +#~ msgstr "複製和克隆" + +#~ msgid "Shared and Unique Borrows" +#~ msgstr "共用借用和專屬借用" + +#~ msgid "Designing a Library" +#~ msgstr "設計程式庫" + +#~ msgid "Iterators and Ownership" +#~ msgstr "疊代器和擁有權" + +#~ msgid "Field Shorthand Syntax" +#~ msgstr "欄位簡寫語法" + +#~ msgid "Variant Payloads" +#~ msgstr "變體負載" + +#~ msgid "Enum Sizes" +#~ msgstr "列舉大小" + +#~ msgid "Method Receiver" +#~ msgstr "方法接收器" + +#~ msgid "Destructuring Structs" +#~ msgstr "解構結構體" + +#~ msgid "Destructuring Arrays" +#~ msgstr "解構陣列" + +#~ msgid "Match Guards" +#~ msgstr "配對守衛" + +#~ msgid "Points and Polygons" +#~ msgstr "點和多邊形" + +#~ msgid "if expressions" +#~ msgstr "if 表達式" + +#~ msgid "if let expressions" +#~ msgstr "if let 運算式" + +#~ msgid "while expressions" +#~ msgstr "while 運算式" + +#~ msgid "for expressions" +#~ msgstr "for 運算式" + +#~ msgid "loop expressions" +#~ msgstr "loop 運算式" + +#~ msgid "match expressions" +#~ msgstr "match 運算式" + +#~ msgid "break & continue" +#~ msgstr "break 和 continue" + +#~ msgid "Option and Result" +#~ msgstr "Option 和 Result" + +#~ msgid "Vec" +#~ msgstr "Vec" + +#~ msgid "HashMap" +#~ msgstr "HashMap" + +#~ msgid "Box" +#~ msgstr "Box" + +#~ msgid "Recursive Data Types" +#~ msgstr "遞迴資料型別" + +#~ msgid "Rc" +#~ msgstr "Rc" + +#~ msgid "Strings and Iterators" +#~ msgstr "字串和疊代器" + +#~ msgid "Generic Methods" +#~ msgstr "泛型方法" + +#~ msgid "Monomorphization" +#~ msgstr "單型化" + +#~ msgid "Default Methods" +#~ msgstr "預設方法" + +#~ msgid "impl Trait" +#~ msgstr "impl Trait" + +#~ msgid "Important Traits" +#~ msgstr "重要特徵" + +#~ msgid "From and Into" +#~ msgstr "From 和 Into" + +#~ msgid "Default" +#~ msgstr "Default" + +#~ msgid "Operators: Add, Mul, ..." +#~ msgstr "運算子:Add、Mul、..." + +#~ msgid "Closures: Fn, FnMut, FnOnce" +#~ msgstr "閉包:Fn、FnMut、FnOnce" + +#~ msgid "A Simple GUI Library" +#~ msgstr "簡易 GUI 程式庫" + +#~ msgid "Catching Stack Unwinding" +#~ msgstr "捕獲解開堆疊的動作" + +#~ msgid "Structured Error Handling" +#~ msgstr "結構化錯誤處理" + +#~ msgid "Propagating Errors with ?" +#~ msgstr "使用 ? 傳播錯誤" + +#~ msgid "Converting Error Types" +#~ msgstr "轉換錯誤型別" + +#~ msgid "Deriving Error Enums" +#~ msgstr "推導錯誤列舉" + +#~ msgid "Adding Context to Errors" +#~ msgstr "為錯誤添加背景資訊" + +#~ msgid "no_std" +#~ msgstr "no_std" + +#~ msgid "alloc" +#~ msgstr "alloc" + +#~ msgid "embedded-hal" +#~ msgstr "embedded-hal" + +#~ msgid "zerocopy" +#~ msgstr "zerocopy" + +#~ msgid "aarch64-paging" +#~ msgstr "aarch64-paging" + +#~ msgid "buddy_system_allocator" +#~ msgstr "buddy_system_allocator" + +#~ msgid "tinyvec" +#~ msgstr "tinyvec" + +#~ msgid "spin" +#~ msgstr "旋轉" + +#~ msgid "Send and Sync" +#~ msgstr "Send 和 Sync" + +#~ msgid "Send" +#~ msgstr "Send" + +#~ msgid "Sync" +#~ msgstr "Sync" + +#~ msgid "Arc" +#~ msgstr "Arc" + +#~ msgid "Mutex" +#~ msgstr "Mutex" + +#~ msgid "async/await" +#~ msgstr "async/await" + +#~ msgid "Pin" +#~ msgstr "釘選" + +#~ msgid "Day 1 Morning" +#~ msgstr "第 1 天上午" + +#~ msgid "Day 1 Afternoon" +#~ msgstr "第 1 天下午" + +#~ msgid "Day 2 Morning" +#~ msgstr "第 2 天上午" + +#~ msgid "Day 2 Afternoon" +#~ msgstr "第 2 天下午" + +#~ msgid "Day 3 Morning" +#~ msgstr "第 3 天上午" + +#~ msgid "Day 3 Afternoon" +#~ msgstr "第 3 天下午" + +#~ msgid "Bare Metal Rust Morning" +#~ msgstr "Rust 裸機開發:上午" + +#~ msgid "Concurrency Morning" +#~ msgstr "並行:上午" + +#~ msgid "Concurrency Afternoon" +#~ msgstr "並行:下午" + +#~ msgid "The course is fast paced and covers a lot of ground:" +#~ msgstr "本課程步調快速,涵蓋許多層面:" + +#~ msgid "Day 1: Basic Rust, ownership and the borrow checker." +#~ msgstr "" +#~ "第 1 天:Rust 基礎知識、擁有權 (ownership) 與借用檢查器 (borrow checker)。" + +#~ msgid "Day 2: Compound data types, pattern matching, the standard library." +#~ msgstr "第 2 天:複合資料型別、模式比對 (pattern matching)、標準程式庫。" + +#~ msgid "Day 3: Traits and generics, error handling, testing, unsafe Rust." +#~ msgstr "" +#~ "第 3 天:特徵 (traits) 與泛型 (generics)、錯誤處理、測試、不安全的 Rust。" + +#~ msgid "Concurrency" +#~ msgstr "並行" + +#~ msgid "" +#~ "```shell\n" +#~ "cargo init concurrency\n" +#~ "cd concurrency\n" +#~ "cargo add tokio --features full\n" +#~ "cargo run\n" +#~ "```" +#~ msgstr "" +#~ "```shell\n" +#~ "cargo init concurrency\n" +#~ "cd concurrency\n" +#~ "cargo add tokio --features full\n" +#~ "cargo run\n" +#~ "```" + +#~ msgid "Rustup (Recommended)" +#~ msgstr "Rustup (建議)" + +#~ msgid "" +#~ "You can follow the instructions to install cargo and rust compiler, among " +#~ "other standard ecosystem tools with the [rustup](https://rust-analyzer." +#~ "github.io/) tool, which is maintained by the Rust Foundation." +#~ msgstr "" +#~ "您可以按照指示安裝 Cargo 和 Rust 編譯器,並運用 Rust Foundation 維護的 " +#~ "[rustup](https://rust-analyzer.github.io/) 工具安裝其他標準生態系統工具。" + +#~ msgid "Package Managers" +#~ msgstr "套件管理員" + +#~ msgid "Debian" +#~ msgstr "Debian" + +#~ msgid "" +#~ "```shell\n" +#~ "$ sudo apt install cargo rust-src rustfmt\n" +#~ "```" +#~ msgstr "" +#~ "```shell\n" +#~ "$ sudo apt install cargo rust-src rustfmt\n" +#~ "```" + +#~ msgid "" +#~ "This will allow \\[rust-analyzer\\]\\[1\\] to jump to the definitions. We " +#~ "suggest using [VS Code](https://code.visualstudio.com/) to edit the code " +#~ "(but any LSP compatible editor works)." +#~ msgstr "" +#~ "這樣一來,\\[rust-analyzer\\]\\[1\\] 就能跳至定義。建議您使用 [VS Code]" +#~ "(https://code.visualstudio.com/) 編輯程式碼,不過任何與 LSP 相容的編輯器都" +#~ "能運作。" + +#~ msgid "" +#~ "Some folks also like to use the [JetBrains](https://www.jetbrains.com/" +#~ "clion/) family of IDEs, which do their own analysis but have their own " +#~ "tradeoffs. If you prefer them, you can install the [Rust Plugin](https://" +#~ "www.jetbrains.com/rust/). Please take note that as of January 2023 " +#~ "debugging only works on the CLion version of the JetBrains IDEA suite." +#~ msgstr "" +#~ "有些人也偏好使用 [JetBrains](https://www.jetbrains.com/clion/) 系列的 " +#~ "IDE,這些工具會自行分析,但也各有缺點。如果您偏好這些工具,可以安裝 [Rust " +#~ "外掛程式](https://www.jetbrains.com/rust/)。請注意,自 2023 年 1 月起,偵" +#~ "錯功能僅適用於 JetBrains IDEA 套件的 CLion 版本。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " println!(\"Edit me!\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " println!(\"Edit me!\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```shell\n" +#~ "% rustc --version\n" +#~ "rustc 1.69.0 (84c898d65 2023-04-16)\n" +#~ "% cargo --version\n" +#~ "cargo 1.69.0 (6e9a83356 2023-04-12)\n" +#~ "```" +#~ msgstr "" +#~ "```shell\n" +#~ "% rustc --version\n" +#~ "rustc 1.69.0 (84c898d65 2023-04-16)\n" +#~ "% cargo --version\n" +#~ "cargo 1.69.0 (6e9a83356 2023-04-12)\n" +#~ "```" + +#~ msgid "" +#~ "```shell\n" +#~ "$ cargo new exercise\n" +#~ " Created binary (application) `exercise` package\n" +#~ "```" +#~ msgstr "" +#~ "```shell\n" +#~ "$ cargo new exercise\n" +#~ " Created binary (application) `exercise` package\n" +#~ "```" + +#~ msgid "" +#~ "```shell\n" +#~ "$ cd exercise\n" +#~ "$ cargo run\n" +#~ " Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" +#~ " Finished dev [unoptimized + debuginfo] target(s) in 0.75s\n" +#~ " Running `target/debug/exercise`\n" +#~ "Hello, world!\n" +#~ "```" +#~ msgstr "" +#~ "```shell\n" +#~ "$ cd exercise\n" +#~ "$ cargo run\n" +#~ " Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" +#~ " Finished dev [unoptimized + debuginfo] target(s) in 0.75s\n" +#~ " Running `target/debug/exercise`\n" +#~ "Hello, world!\n" +#~ "```" + +#~ msgid "" +#~ "```rust\n" +#~ "fn main() {\n" +#~ " println!(\"Edit me!\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust\n" +#~ "fn main() {\n" +#~ " println!(\"Edit me!\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```shell\n" +#~ "$ cargo run\n" +#~ " Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" +#~ " Finished dev [unoptimized + debuginfo] target(s) in 0.24s\n" +#~ " Running `target/debug/exercise`\n" +#~ "Edit me!\n" +#~ "```" +#~ msgstr "" +#~ "```shell\n" +#~ "$ cargo run\n" +#~ " Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)\n" +#~ " Finished dev [unoptimized + debuginfo] target(s) in 0.24s\n" +#~ " Running `target/debug/exercise`\n" +#~ "Edit me!\n" +#~ "```" + +#~ msgid "" +#~ "Memory management: stack vs heap, manual memory management, scope-based " +#~ "memory management, and garbage collection." +#~ msgstr "" +#~ "記憶體管理:堆疊和堆積、手動管理記憶體、範圍式記憶體管理,以及垃圾收集。" + +#~ msgid "" +#~ "Ownership: move semantics, copying and cloning, borrowing, and lifetimes." +#~ msgstr "擁有權:轉移語意、複製、借用,以及生命週期。" + +#~ msgid "" +#~ "The idea for the first day is to show _just enough_ of Rust to be able to " +#~ "speak about the famous borrow checker. The way Rust handles memory is a " +#~ "major feature and we should show students this right away." +#~ msgstr "" +#~ "第一天的規畫是說明 Rust 基礎概念,「只要剛好」能介紹到著名的借用檢查器就行" +#~ "了。Rust 處理記憶體的方式是一大特色,我們應該立即向學生展示這一點。" + +#~ msgid "" +#~ "If you're teaching this in a classroom, this is a good place to go over " +#~ "the schedule. We suggest splitting the day into two parts (following the " +#~ "slides):" +#~ msgstr "" +#~ "如果您是在教室授課,就很適合參考這裡的時間表。建議您將一天分為兩部分 (根據" +#~ "投影片安排):" + +#~ msgid "Morning: 9:00 to 12:00," +#~ msgstr "上午:9 點到 12 點" + +#~ msgid "Afternoon: 13:00 to 16:00." +#~ msgstr "下午:1 點到 4 點" + +#~ msgid "" +#~ "You can of course adjust this as necessary. Please make sure to include " +#~ "breaks, we recommend a break every hour!" +#~ msgstr "" +#~ "您當然可以視需要調整這個時間表。但請務必要加入休息時段,建議每小時休息一" +#~ "次!" + +#~ msgid "Here is a small example program in Rust:" +#~ msgstr "以下是使用 Rust 語言的簡短範例程式:" + +#~ msgid "" +#~ "The code implements the Collatz conjecture: it is believed that the loop " +#~ "will always end, but this is not yet proved. Edit the code and play with " +#~ "different inputs." +#~ msgstr "" +#~ "這是「考拉茲猜想」的實作程式碼,考拉茲相信迴圈不管怎樣終會結束,但這尚未得" +#~ "證。您可以編輯該程式碼,試著輸入不同內容。" + +#~ msgid "" +#~ "Explain that all variables are statically typed. Try removing `i32` to " +#~ "trigger type inference. Try with `i8` instead and trigger a runtime " +#~ "integer overflow." +#~ msgstr "" +#~ "解釋所有變數都是靜態的。試著移除 `i32` 來觸發型別推斷。接著嘗試改用 `i8`," +#~ "並觸發執行階段的整數溢位現象。" + +#~ msgid "Change `let mut x` to `let x`, discuss the compiler error." +#~ msgstr "將 `let mut x` 改為 `let x`,討論編譯器錯誤。" + +#~ msgid "" +#~ "Show how `print!` gives a compilation error if the arguments don't match " +#~ "the format string." +#~ msgstr "說明如果引數與格式字串不符,`print!` 會如何呈現編譯錯誤。" + +#~ msgid "" +#~ "Show how you need to use `{}` as a placeholder if you want to print an " +#~ "expression which is more complex than just a single variable." +#~ msgstr "" +#~ "說明要輸出比單一變數更複雜的運算式時,需如何使用 `{}` 做為預留位置。" + +#~ msgid "" +#~ "Show the students the standard library, show them how to search for `std::" +#~ "fmt` which has the rules of the formatting mini-language. It's important " +#~ "that the students become familiar with searching in the standard library." +#~ msgstr "" +#~ "向學生介紹標準程式庫,示範如何搜尋具有格式化迷你語言規則的 `std::fmt`。請" +#~ "務必確保學生熟悉如何在標準程式庫中搜尋。" + +#~ msgid "Compile time memory safety." +#~ msgstr "在編譯期間確保記憶體安全性。" + +#~ msgid "Lack of undefined runtime behavior." +#~ msgstr "沒有未定義的執行階段行為。" + +#~ msgid "Modern language features." +#~ msgstr "現代的語言特色。" + +#~ msgid "Static memory management at compile time:" +#~ msgstr "編譯期間的靜態記憶體管理機制好處多多,包括:" + +#~ msgid "No memory leaks (_mostly_, see notes)." +#~ msgstr "不會造成記憶體流失 (「一般」來說是這樣,請參閱附註)。" + +#~ msgid "" +#~ "It is possible to produce memory leaks in (safe) Rust. Some examples are:" +#~ msgstr "" +#~ "在 (安全的) Rust 範疇內,可能還是有機會造成記憶體流失。以下是一些例子:" + +#~ msgid "" +#~ "You can use [`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box." +#~ "html#method.leak) to leak a pointer. A use of this could be to get " +#~ "runtime-initialized and runtime-sized static variables" +#~ msgstr "" +#~ "您可能會使用 [`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box." +#~ "html#method.leak),以致洩漏指標。如果您為了取得在執行階段中初始化或設定大" +#~ "小的靜態變數,就可能發生這個情況。" + +#~ msgid "" +#~ "You can use [`std::mem::forget`](https://doc.rust-lang.org/std/mem/fn." +#~ "forget.html) to make the compiler \"forget\" about a value (meaning the " +#~ "destructor is never run)." +#~ msgstr "" +#~ "您可能會透過 [`std::mem::forget`](https://doc.rust-lang.org/std/mem/fn." +#~ "forget.html) 讓編譯器「忘記」某個值 (亦即解構函式永遠不會執行)。" + +#~ msgid "" +#~ "You can also accidentally create a [reference cycle](https://doc.rust-" +#~ "lang.org/book/ch15-06-reference-cycles.html) with `Rc` or `Arc`." +#~ msgstr "" +#~ "您也可能會不小心使用 `Rc` 或 `Arc` 建立[參照循環](https://doc.rust-lang." +#~ "org/book/ch15-06-reference-cycles.html)。" + +#~ msgid "" +#~ "In fact, some will consider infinitely populating a collection a memory " +#~ "leak and Rust does not protect from those." +#~ msgstr "" +#~ "事實上,有些人會認為無限地填充集合是一種記憶體流失,而 Rust 並不能避免這種" +#~ "情況。" + +#~ msgid "" +#~ "For the purpose of this course, \"No memory leaks\" should be understood " +#~ "as \"Pretty much no _accidental_ memory leaks\"." +#~ msgstr "" +#~ "因此,以本課程的宗旨來說,「沒有記憶體流失」應理解為「幾乎沒有『意外的』記" +#~ "憶體流失」。" + +#~ msgid "" +#~ "Bounds checking cannot be disabled with a compiler flag. It can also not " +#~ "be disabled directly with the `unsafe` keyword. However, `unsafe` allows " +#~ "you to call functions such as `slice::get_unchecked` which does not do " +#~ "bounds checking." +#~ msgstr "" +#~ "您無法使用編譯器參數停用邊界檢查,也無法直接透過 `unsafe` 關鍵字停用。不" +#~ "過,您可以使用 `unsafe` 呼叫 `slice::get_unchecked` 這類不執行邊界檢查的函" +#~ "式。" + +#~ msgid "Language Features" +#~ msgstr "語言特色" + +#~ msgid "Tooling" +#~ msgstr "工具" + +#~ msgid "" +#~ "Zero-cost abstractions, similar to C++, means that you don't have to " +#~ "'pay' for higher-level programming constructs with memory or CPU. For " +#~ "example, writing a loop using `for` should result in roughly the same low " +#~ "level instructions as using the `.iter().fold()` construct." +#~ msgstr "" +#~ "與 C++ 類似,零成本抽象化機制是指您不必為使用記憶體或 CPU 的高階程式設計結" +#~ "構「付費」。舉例來說,使用 `for` 編寫迴圈時,應產生與使用 `.iter()." +#~ "fold()` 結構大致相同的低階指示。" + +#~ msgid "" +#~ "It may be worth mentioning that Rust enums are 'Algebraic Data Types', " +#~ "also known as 'sum types', which allow the type system to express things " +#~ "like `Option` and `Result`." +#~ msgstr "" +#~ "值得一提的是,Rust 列舉屬於「代數資料型別」(也稱為「加總型別」),可讓型別" +#~ "系統表達 `Option` 和 `Result` 等項目。" + +#~ msgid "" +#~ "Remind people to read the errors --- many developers have gotten used to " +#~ "ignore lengthy compiler output. The Rust compiler is significantly more " +#~ "talkative than other compilers. It will often provide you with " +#~ "_actionable_ feedback, ready to copy-paste into your code." +#~ msgstr "" +#~ "提醒使用者詳讀錯誤訊息,許多開發人員已習慣忽略冗長的編譯器輸出結果。Rust " +#~ "編譯器的表達能力比其他編譯器高出許多,通常都會提供「實用」的意見回饋,您可" +#~ "以直接將其複製貼到程式碼中。" + +#~ msgid "" +#~ "The Rust standard library is small compared to languages like Java, " +#~ "Python, and Go. Rust does not come with several things you might consider " +#~ "standard and essential:" +#~ msgstr "" +#~ "與 Java、Python 和 Go 等語言相比,Rust 標準程式庫較小。Rust 並不提供某些您" +#~ "可能認為是標準和基本項目的內容:" + +#~ msgid "a random number generator, but see [rand](https://docs.rs/rand/)." +#~ msgstr "隨機號碼產生器,請參閱 [rand](https://docs.rs/rand/)。" + +#~ msgid "support for SSL or TLS, but see [rusttls](https://docs.rs/rustls/)." +#~ msgstr "SSL 或 TLS 支援,請參閱 [rusttls](https://docs.rs/rustls/)。" + +#~ msgid "support for JSON, but see [serde_json](https://docs.rs/serde_json/)." +#~ msgstr "JSON 支援,請參閱 [serde_json](https://docs.rs/serde_json/)。" + +#~ msgid "" +#~ "The reasoning behind this is that functionality in the standard library " +#~ "cannot go away, so it has to be very stable. For the examples above, the " +#~ "Rust community is still working on finding the best solution --- and " +#~ "perhaps there isn't a single \"best solution\" for some of these things." +#~ msgstr "" +#~ "未提供此支援的原因是,標準程式庫中的功能無法移除,因此必須相當穩定。對於以" +#~ "上範例,Rust 社群仍在努力尋找最佳解決方案,但其中某幾個例子或許並沒有單一" +#~ "的「最佳解決方案」。" + +#~ msgid "" +#~ "Rust comes with a built-in package manager in the form of Cargo and this " +#~ "makes it trivial to download and compile third-party crates. A " +#~ "consequence of this is that the standard library can be smaller." +#~ msgstr "" +#~ "Rust 內建採用 Cargo 形式的套件管理工具,因此可讓您輕鬆下載及編譯第三方 " +#~ "Crate。這樣一來,就可以縮小標準程式庫的規模。" + +#~ msgid "" +#~ "Discovering good third-party crates can be a problem. Sites like help with this by letting you compare health metrics for crates " +#~ "to find a good and trusted one." +#~ msgstr "" +#~ "如何找到理想的第三方 Crate 可能是一大問題。但請放心, 這" +#~ "類網站可協助您比較 Crate 的健康指標,找出優質且值得信賴的 Crate。" + +#~ msgid "" +#~ "[rust-analyzer](https://rust-analyzer.github.io/) is a well supported LSP " +#~ "implementation used in major IDEs and text editors." +#~ msgstr "" +#~ "[rust-analyzer](https://rust-analyzer.github.io/) 是廣受支援的 LSP 實作項" +#~ "目,適用於主要的 IDE 和文字編輯器。" + +#~ msgid "Much of the Rust syntax will be familiar to you from C, C++ or Java:" +#~ msgstr "如果您有 C、C++ 或 Java 基礎,會覺得大部分的 Rust 語法都似曾相識:" + +#~ msgid "Blocks and scopes are delimited by curly braces." +#~ msgstr "區塊和範圍會以大括號分隔。" + +#~ msgid "" +#~ "Line comments are started with `//`, block comments are delimited by `/" +#~ "* ... */`." +#~ msgstr "行註解以 `//` 開頭,區塊註解則以 `/* ... */` 分隔。" + +#~ msgid "Keywords like `if` and `while` work the same." +#~ msgstr "`if` 和 `while` 等關鍵字的功用相同。" + +#~ msgid "Variable assignment is done with `=`, comparison is done with `==`." +#~ msgstr "變數指派作業透過 `=` 完成,等於運算則透過 `==` 完成。" + +#~ msgid "`\"foo\"`, `\"two\\nlines\"`" +#~ msgstr "`\"foo\"`、`\"two\\nlines\"`" + +#~ msgid "`[T; N]`" +#~ msgstr "`[T; N]`" + +#~ msgid "`[20, 30, 40]`, `[0; 3]`" +#~ msgstr "`[20, 30, 40]`、`[0; 3]`" + +#~ msgid "`()`, `(T,)`, `(T1, T2)`, ..." +#~ msgstr "`()`、`(T,)`、`(T1, T2)`..." + +#~ msgid "`()`, `('x',)`, `('x', 1.2)`, ..." +#~ msgstr "`()`、`('x',)`、`('x', 1.2)`..." + +#~ msgid "Array assignment and access:" +#~ msgstr "陣列指派與存取:" + +#~ msgid "Tuple assignment and access:" +#~ msgstr "元組指派與存取:" + +#~ msgid "Arrays:" +#~ msgstr "陣列:" + +#~ msgid "Tuples:" +#~ msgstr "元組:" + +#~ msgid "" +#~ "The empty tuple `()` is also known as the \"unit type\". It is both a " +#~ "type, and the only valid value of that type - that is to say both the " +#~ "type and its value are expressed as `()`. It is used to indicate, for " +#~ "example, that a function or expression has no return value, as we'll see " +#~ "in a future slide. " +#~ msgstr "" +#~ "空白元組 `()` 也稱為「單位型別」。它既是型別,也是該型別唯一的有效值,亦即" +#~ "該型別及其值都以 `()` 表示。舉例來說,空白元組可用於表示函式或運算式沒有任" +#~ "何回傳值,我們會在之後的投影片看到這個例子。" + +#~ msgid "" +#~ "You can think of it as `void` that can be familiar to you from other " +#~ "programming languages." +#~ msgstr "您可以將其視為其他程式設計語言中的 `void`,可能就不會感到陌生。" + +#~ msgid "Like C++, Rust has references:" +#~ msgstr "和 C++ 一樣,Rust 具有參照:" + +#~ msgid "" +#~ "We must dereference `ref_x` when assigning to it, similar to C and C++ " +#~ "pointers." +#~ msgstr "指派至 `ref_x` 時,我們必須對其解除參照,這類似於 C 和 C++ 指標。" + +#~ msgid "" +#~ "References that are declared as `mut` can be bound to different values " +#~ "over their lifetime." +#~ msgstr "宣告為 `mut` 的參照可在其生命週期內綁定至不同的值。" + +#~ msgid "A reference is said to \"borrow\" the value it refers to." +#~ msgstr "所謂參照項目,可說是「借用」其參照的值。" + +#~ msgid "" +#~ "Rust is tracking the lifetimes of all references to ensure they live long " +#~ "enough." +#~ msgstr "Rust 會追蹤所有參照項目的生命週期,確保其存留時間夠長。" + +#~ msgid "`String` vs `str`" +#~ msgstr "`String` 和 `str`" + +#~ msgid "We can now understand the two string types in Rust:" +#~ msgstr "現在,我們可以瞭解 Rust 中有兩種字串型別:" + +#~ msgid "" +#~ "You can borrow `&str` slices from `String` via `&` and optionally range " +#~ "selection." +#~ msgstr "您可以透過 `&str` 和可選的範圍選項,從 `String` 借用 `&str` 切片。" + +#~ msgid "" +#~ "A Rust version of the famous [FizzBuzz](https://en.wikipedia.org/wiki/" +#~ "Fizz_buzz) interview question:" +#~ msgstr "" +#~ "這是知名面試問題 [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) 的 " +#~ "Rust 版本:" + +#~ msgid "" +#~ "We refer in `main` to a function written below. Neither forward " +#~ "declarations nor headers are necessary. " +#~ msgstr "我們在 `main` 中參照以下所寫的函式。不需前向宣告,也不需標頭。" + +#~ msgid "" +#~ "The range expression in the `for` loop in `print_fizzbuzz_to()` contains " +#~ "`=n`, which causes it to include the upper bound." +#~ msgstr "" +#~ "`print_fizzbuzz_to()` 中 `for` 迴圈的範圍運算式含有 `=n`,因此會包含上限" +#~ "值。" + +#~ msgid "" +#~ "All language items in Rust can be documented using special `///` syntax." +#~ msgstr "Rust 中的所有語言項目都能以特殊的 `///` 語法來描述使用方法。" + +#~ msgid "" +#~ "This course does not include rustdoc on slides, just to save space, but " +#~ "in real code they should be present." +#~ msgstr "" +#~ "本課程未在投影片中加入 rustdoc 只是為了節省空間,但在實際程式碼中不應這麼" +#~ "做。" + +#~ msgid "" +#~ "Inner doc comments are discussed later (in the page on modules) and need " +#~ "not be addressed here." +#~ msgstr "文件內註解會在稍後討論 (在模組相關頁面中),因此這裡不需提到。" + +#~ msgid "" +#~ "Methods are functions associated with a type. The `self` argument of a " +#~ "method is an instance of the type it is associated with:" +#~ msgstr "" +#~ "方法是與型別相關聯的函式。方法的 `self` 引數是與其相關聯的型別執行個體:" + +#~ msgid "" +#~ "We will look much more at methods in today's exercise and in tomorrow's " +#~ "class." +#~ msgstr "我們將在今天的練習和明天的課程中深入探討更多方法。" + +#~ msgid "Function Overloading" +#~ msgstr "函式超載" + +#~ msgid "Overloading is not supported:" +#~ msgstr "Rust 不支援超載:" + +#~ msgid "Always takes a fixed number of parameters." +#~ msgstr "一律採用固定數量的參數。" + +#~ msgid "Default values are not supported:" +#~ msgstr "不支援預設值:" + +#~ msgid "All call sites have the same number of arguments." +#~ msgstr "所有呼叫的引數數目都相同。" + +#~ msgid "Macros are sometimes used as an alternative." +#~ msgstr "有時系統會改用巨集。" + +#~ msgid "However, function parameters can be generic:" +#~ msgstr "不過,函式參數可能為泛型:" + +#~ msgid "" +#~ "When using generics, the standard library's `Into` can provide a kind " +#~ "of limited polymorphism on argument types. We will see more details in a " +#~ "later section." +#~ msgstr "" +#~ "使用泛型時,標準程式庫的 `Into` 可以為引數型別提供一種受限的多態性。我" +#~ "們會在後續章節中進一步說明。" + +#~ msgid "Day 1: Morning Exercises" +#~ msgstr "第 1 天:上午練習" + +#~ msgid "In these exercises, we will explore two parts of Rust:" +#~ msgstr "在這些練習中,我們將探索 Rust 的兩個部分:" + +#~ msgid "Implicit conversions between types." +#~ msgstr "不同型別間的隱含轉換。" + +#~ msgid "Arrays and `for` loops." +#~ msgstr "陣列和 `for` 迴圈。" + +#~ msgid "A few things to consider while solving the exercises:" +#~ msgstr "練習解題時的注意事項:" + +#~ msgid "" +#~ "Use a local Rust installation, if possible. This way you can get auto-" +#~ "completion in your editor. See the page about [Using Cargo](../../cargo." +#~ "md) for details on installing Rust." +#~ msgstr "" +#~ "如果可以,請在本機安裝 Rust。這樣即可在編輯器中使用自動完成功能。如要進一" +#~ "步瞭解如何安裝 Rust,請參閱「[使用 Cargo](../../cargo.md)」。" + +#~ msgid "Alternatively, use the Rust Playground." +#~ msgstr "或者,您也可以使用 Rust Playground。" + +#~ msgid "" +#~ "The code snippets are not editable on purpose: the inline code snippets " +#~ "lose their state if you navigate away from the page." +#~ msgstr "" +#~ "系統會特意將程式碼片段設為無法編輯:如果您離開網頁,內嵌程式碼片段的狀態就" +#~ "會遺失。" + +#~ msgid "" +#~ "Rust will not automatically apply _implicit conversions_ between types " +#~ "([unlike C++](https://en.cppreference.com/w/cpp/language/" +#~ "implicit_conversion)). You can see this in a program like this:" +#~ msgstr "" +#~ "Rust 不會自動在型別間套用「隱含轉換」 ([與 C++ 不同](https://en." +#~ "cppreference.com/w/cpp/language/implicit_conversion))。您可以在類似下方的" +#~ "程式中發現這點:" + +#~ msgid "" +#~ "The Rust integer types all implement the [`From`](https://doc.rust-" +#~ "lang.org/std/convert/trait.From.html) and [`Into`](https://doc.rust-" +#~ "lang.org/std/convert/trait.Into.html) traits to let us convert between " +#~ "them. The `From` trait has a single `from()` method and similarly, the " +#~ "`Into` trait has a single `into()` method. Implementing these traits " +#~ "is how a type expresses that it can be converted into another type." +#~ msgstr "" +#~ "Rust 整數型別全都會實作 [`From`](https://doc.rust-lang.org/std/convert/" +#~ "trait.From.html) 和 [`Into`](https://doc.rust-lang.org/std/convert/" +#~ "trait.Into.html) 特徵,方便我們在兩者間轉換。`From` 特徵有單一的 " +#~ "`from() 方法;同樣地,`Into` 特徵也有單一的 `into()` 方法。實作這些特" +#~ "徵,是型別表示自身可轉換為另一種型別的方式。" + +#~ msgid "" +#~ "The standard library has an implementation of `From for i16`, which " +#~ "means that we can convert a variable `x` of type `i8` to an `i16` by " +#~ "calling `i16::from(x)`. Or, simpler, with `x.into()`, because `From " +#~ "for i16` implementation automatically create an implementation of " +#~ "`Into for i8`." +#~ msgstr "" +#~ "標準程式庫會內有 `From for i16` 實作項目,這表示我們可以呼叫 `i16::" +#~ "from(x)`,將類型 `i8` 的變數 `x` 轉換為 `i16`。或者,更簡單的方法是使用 " +#~ "`x.into()`,因為 `From for i16` 實作會自動建立 `Into for i8` 的實" +#~ "作。" + +#~ msgid "" +#~ "The same applies for your own `From` implementations for your own types, " +#~ "so it is sufficient to only implement `From` to get a respective `Into` " +#~ "implementation automatically." +#~ msgstr "" +#~ "這同樣適用於您自身型別專屬的 `From` 實作,因此只要實作 `From`,就能自動取" +#~ "得相應的 `Into` 實作。" + +#~ msgid "Execute the above program and look at the compiler error." +#~ msgstr "執行上述程式,並查看編譯器錯誤。" + +#~ msgid "Update the code above to use `into()` to do the conversion." +#~ msgstr "更新上述程式碼,使用 `into()` 執行轉換。" + +#~ msgid "" +#~ "Change the types of `x` and `y` to other things (such as `f32`, `bool`, " +#~ "`i128`) to see which types you can convert to which other types. Try " +#~ "converting small types to big types and the other way around. Check the " +#~ "[standard library documentation](https://doc.rust-lang.org/std/convert/" +#~ "trait.From.html) to see if `From` is implemented for the pairs you " +#~ "check." +#~ msgstr "" +#~ "將 `x` 和 `y` 的型別變更為其他型別 (例如 `f32`、`bool`、`i128`),查看這些" +#~ "型別可以轉換成其他哪些型別。不妨試著將小型別轉換成大型別,反之亦然。接著參" +#~ "閱[標準程式庫說明文件](https://doc.rust-lang.org/std/convert/trait.From." +#~ "html),瞭解系統是否已為您查看的配對實作 `From`。" + +#~ msgid "Arrays and `for` Loops" +#~ msgstr "陣列和 `for` 迴圈" + +#~ msgid "We saw that an array can be declared like this:" +#~ msgstr "我們已瞭解陣列的宣告方式可能如下:" + +#~ msgid "" +#~ "You can print such an array by asking for its debug representation with " +#~ "`{:?}`:" +#~ msgstr "您可以使用 `{:?}` 偵錯表示法輸出這樣的陣列:" + +#~ msgid "" +#~ "Rust lets you iterate over things like arrays and ranges using the `for` " +#~ "keyword:" +#~ msgstr "您可在 Rust 中使用 `for` 關鍵字,對陣列和範圍等項目進行疊代作業:" + +#~ msgid "Bonus Question" +#~ msgstr "加分題" + +#~ msgid "" +#~ "Could you use `&[i32]` slices instead of hard-coded 3 × 3 matrices for " +#~ "your argument and return types? Something like `&[&[i32]]` for a two-" +#~ "dimensional slice-of-slices. Why or why not?" +#~ msgstr "" +#~ "您是否能夠使用 `&[i32]` 切片 (而非硬式編碼的 3 × 3 矩陣) 做為引數和傳回型" +#~ "別?例如針對二維切片使用 `&[&[i32]]`。原因為何?" + +#~ msgid "" +#~ "See the [`ndarray` crate](https://docs.rs/ndarray/) for a production " +#~ "quality implementation." +#~ msgstr "" +#~ "請參閱 [`ndarray` Crate](https://docs.rs/ndarray/),瞭解如何在確保實際工作" +#~ "環境品質的情況下實作。" + +#~ msgid "" +#~ "The solution and the answer to the bonus section are available in the " +#~ "[Solution](solutions-morning.md#arrays-and-for-loops) section." +#~ msgstr "" +#~ "如需加分題的解決方案和答案,請前往「[解決方案](solutions-morning." +#~ "md#arrays-and-for-loops)」一節。" + +#~ msgid "" +#~ "Due to type inference the `i32` is optional. We will gradually show the " +#~ "types less and less as the course progresses." +#~ msgstr "" +#~ "由於型別推論的關係,`i32` 為選用項目。隨著課程進行,我們會逐漸減少示範型別" +#~ "的比例。" + +#~ msgid "" +#~ "The following code tells the compiler to copy into a certain generic " +#~ "container without the code ever explicitly specifying the contained type, " +#~ "using `_` as a placeholder:" +#~ msgstr "" +#~ "以下程式碼會指示編譯器使用 `_` 做為預留位置,進而複製到特定泛型容器中,而" +#~ "無須明確指出包含的型別:" + +#~ msgid "Static and Constant Variables" +#~ msgstr "靜態和常數變數" + +#~ msgid "" +#~ "The following code demonstrates why the compiler can't simply reuse " +#~ "memory locations when shadowing an immutable variable in a scope, even if " +#~ "the type does not change." +#~ msgstr "" +#~ "下列程式碼說明遮蔽範圍中不可變動的變數時,為何編譯器就是無法重複使用記憶體" +#~ "位置 (即使型別未變更也一樣)。" + +#~ msgid "First, let's refresh how memory management works." +#~ msgstr "首先,讓我們回顧記憶體管理的運作方式。" + +#~ msgid "The Stack vs The Heap" +#~ msgstr "堆疊與堆積" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let s1 = String::from(\"Hello\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let s1 = String::from(\"Hello\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut s1 = String::from(\"Hello\");\n" +#~ " s1.push(' ');\n" +#~ " s1.push_str(\"world\");\n" +#~ " // DON'T DO THIS AT HOME! For educational purposes only.\n" +#~ " // String provides no guarantees about its layout, so this could lead " +#~ "to\n" +#~ " // undefined behavior.\n" +#~ " unsafe {\n" +#~ " let (capacity, ptr, len): (usize, usize, usize) = std::mem::" +#~ "transmute(s1);\n" +#~ " println!(\"ptr = {ptr:#x}, len = {len}, capacity = " +#~ "{capacity}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut s1 = String::from(\"Hello\");\n" +#~ " s1.push(' ');\n" +#~ " s1.push_str(\"world\");\n" +#~ " // DON'T DO THIS AT HOME! For educational purposes only.\n" +#~ " // String provides no guarantees about its layout, so this could lead " +#~ "to\n" +#~ " // undefined behavior.\n" +#~ " unsafe {\n" +#~ " let (capacity, ptr, len): (usize, usize, usize) = std::mem::" +#~ "transmute(s1);\n" +#~ " println!(\"ptr = {ptr:#x}, len = {len}, capacity = " +#~ "{capacity}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "You allocate and deallocate heap memory yourself." +#~ msgstr "您可以自行配置及釋放堆積記憶體。" + +#~ msgid "" +#~ "If not done with care, this can lead to crashes, bugs, security " +#~ "vulnerabilities, and memory leaks." +#~ msgstr "如果操作時不夠小心,可能會導致當機、錯誤、安全漏洞和記憶體泄漏。" + +#~ msgid "C Example" +#~ msgstr "C 範例" + +#~ msgid "You must call `free` on every pointer you allocate with `malloc`:" +#~ msgstr "使用 `malloc` 配置每個指標時,都必須呼叫 `free`:" + +#~ msgid "" +#~ "```c\n" +#~ "void foo(size_t n) {\n" +#~ " int* int_array = (int*)malloc(n * sizeof(int));\n" +#~ " //\n" +#~ " // ... lots of code\n" +#~ " //\n" +#~ " free(int_array);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```c\n" +#~ "void foo(size_t n) {\n" +#~ " int* int_array = (int*)malloc(n * sizeof(int));\n" +#~ " //\n" +#~ " // ... lots of code\n" +#~ " //\n" +#~ " free(int_array);\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "Memory is leaked if the function returns early between `malloc` and " +#~ "`free`: the pointer is lost and we cannot deallocate the memory." +#~ msgstr "" +#~ "如果函式在 `malloc` 和 `free` 之間提早傳回記憶體,就會發生記憶體泄漏:指標" +#~ "遺失,我們也無法釋放記憶體。" + +#~ msgid "" +#~ "Constructors and destructors let you hook into the lifetime of an object." +#~ msgstr "建構函式和解構函式可讓您掌握物件的生命週期。" + +#~ msgid "" +#~ "By wrapping a pointer in an object, you can free memory when the object " +#~ "is destroyed. The compiler guarantees that this happens, even if an " +#~ "exception is raised." +#~ msgstr "" +#~ "只要在物件中包裝指標,即可在物件刪除時釋放記憶體。即使發生例外狀況,編譯器" +#~ "仍會保證執行這項作業。" + +#~ msgid "" +#~ "This is often called _resource acquisition is initialization_ (RAII) and " +#~ "gives you smart pointers." +#~ msgstr "這通常稱為「資源取得即初始化」(RAII),且會提供智慧指標。" + +#~ msgid "" +#~ "```c++\n" +#~ "void say_hello(std::unique_ptr person) {\n" +#~ " std::cout << \"Hello \" << person->name << std::endl;\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```c++\n" +#~ "void say_hello(std::unique_ptr person) {\n" +#~ " std::cout << \"Hello \" << person->name << std::endl;\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "The `std::unique_ptr` object is allocated on the stack, and points to " +#~ "memory allocated on the heap." +#~ msgstr "`std::unique_ptr` 物件會在堆疊上配置,並指向在堆積上配置的記憶體。" + +#~ msgid "" +#~ "At the end of `say_hello`, the `std::unique_ptr` destructor will run." +#~ msgstr "`say_hello` 結束時,`std::unique_ptr` 解構函式就會執行。" + +#~ msgid "The destructor frees the `Person` object it points to." +#~ msgstr "解構函式會釋放其指向的 `Person` 物件。" + +#~ msgid "" +#~ "Special move constructors are used when passing ownership to a function:" +#~ msgstr "將所有權傳遞至函式時,系統會使用特殊的移動建構函式:" + +#~ msgid "" +#~ "```c++\n" +#~ "std::unique_ptr person = find_person(\"Carla\");\n" +#~ "say_hello(std::move(person));\n" +#~ "```" +#~ msgstr "" +#~ "```c++\n" +#~ "std::unique_ptr person = find_person(\"Carla\");\n" +#~ "say_hello(std::move(person));\n" +#~ "```" + +#~ msgid "" +#~ "An alternative to manual and scope-based memory management is automatic " +#~ "memory management:" +#~ msgstr "" +#~ "除了手動記憶體管理和作用域式記憶體管理之外,自動記憶體管理是另一種做法:" + +#~ msgid "The programmer never allocates or deallocates memory explicitly." +#~ msgstr "程式設計師一律不會明確配置或釋放記憶體。" + +#~ msgid "" +#~ "A garbage collector finds unused memory and deallocates it for the " +#~ "programmer." +#~ msgstr "垃圾收集器會找到未使用的記憶體,並釋放給程式設計師。" + +#~ msgid "Java Example" +#~ msgstr "Java 範例" + +#~ msgid "The `person` object is not deallocated after `sayHello` returns:" +#~ msgstr "`sayHello` 傳回後,系統不會釋放 `person` 物件:" + +#~ msgid "" +#~ "```java\n" +#~ "void sayHello(Person person) {\n" +#~ " System.out.println(\"Hello \" + person.getName());\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```java\n" +#~ "void sayHello(Person person) {\n" +#~ " System.out.println(\"Hello \" + person.getName());\n" +#~ "}\n" +#~ "```" + +#~ msgid "Memory Management in Rust" +#~ msgstr "Rust 中的記憶體管理" + +#~ msgid "Memory management in Rust is a mix:" +#~ msgstr "Rust 中的記憶體管理融合了以下特色:" + +#~ msgid "Safe and correct like Java, but without a garbage collector." +#~ msgstr "像 Java 一樣安全又正確,但沒有垃圾回收機制。" + +#~ msgid "" +#~ "Depending on which abstraction (or combination of abstractions) you " +#~ "choose, can be a single unique pointer, reference counted, or atomically " +#~ "reference counted." +#~ msgstr "" +#~ "可以是單一不重複指標、採用參考計數或採用原子參考計數,須視您選擇的抽象方" +#~ "法 (或抽象方法組合) 而定。" + +#~ msgid "Scope-based like C++, but the compiler enforces full adherence." +#~ msgstr "像 C++ 一樣的作用域式管理,但編譯器會強制遵循完整規定。" + +#~ msgid "" +#~ "A Rust user can choose the right abstraction for the situation, some even " +#~ "have no cost at runtime like C." +#~ msgstr "" +#~ "Rust 使用者可選擇適合情境的抽象方法,部分方法甚至像 C 一樣在執行階段無額外" +#~ "成本。" + +#~ msgid "It achieves this by modeling _ownership_ explicitly." +#~ msgstr "實現這種記憶體管理的方法是明確建立「所有權」模型。" + +#~ msgid "" +#~ "If asked how at this point, you can mention that in Rust this is usually " +#~ "handled by RAII wrapper types such as [Box](https://doc.rust-lang.org/std/" +#~ "boxed/struct.Box.html), [Vec](https://doc.rust-lang.org/std/vec/struct." +#~ "Vec.html), [Rc](https://doc.rust-lang.org/std/rc/struct.Rc.html), or [Arc]" +#~ "(https://doc.rust-lang.org/std/sync/struct.Arc.html). These encapsulate " +#~ "ownership and memory allocation via various means, and prevent the " +#~ "potential errors in C." +#~ msgstr "" +#~ "如果這時學員詢問相關做法,您可以表示這在 Rust 中通常會以 RAII 包裝函式型別" +#~ "處理,例如 [Box](https://doc.rust-lang.org/std/boxed/struct.Box.html)、" +#~ "[Vec](https://doc.rust-lang.org/std/vec/struct.Vec.html)、[Rc](https://" +#~ "doc.rust-lang.org/std/rc/struct.Rc.html) 或 [Arc](https://doc.rust-lang." +#~ "org/std/sync/struct.Arc.html)。這些型別會透過多種方法封裝所有權和記憶體配" +#~ "置,防止在 C 中可能出現的錯誤。" + +#~ msgid "" +#~ "You may be asked about destructors here, the [Drop](https://doc.rust-lang." +#~ "org/std/ops/trait.Drop.html) trait is the Rust equivalent." +#~ msgstr "" +#~ "這時學員可能會詢問解構函式,Rust 中的類似項目就是 [Drop](https://doc.rust-" +#~ "lang.org/std/ops/trait.Drop.html) 特徵。" + +#~ msgid "Here is a rough comparison of the memory management techniques." +#~ msgstr "以下概略比較各種記憶體管理技巧。" + +#~ msgid "Pros of Different Memory Management Techniques" +#~ msgstr "不同記憶體管理技巧的優點" + +#, fuzzy +#~ msgid "Manual like C:" +#~ msgstr "手動管理,例如 C:" + +#, fuzzy +#~ msgid "No runtime overhead." +#~ msgstr "沒有執行階段負擔。" + +#, fuzzy +#~ msgid "Automatic like Java:" +#~ msgstr "自動管理,例如 Java:" + +#, fuzzy +#~ msgid "Fully automatic." +#~ msgstr "完全自動化。" + +#, fuzzy +#~ msgid "Safe and correct." +#~ msgstr "安全又正確。" + +#, fuzzy +#~ msgid "Scope-based like C++:" +#~ msgstr "作用域式管理,例如 C++:" + +#, fuzzy +#~ msgid "Partially automatic." +#~ msgstr "部分自動化。 \\*沒有執行階段負擔。" + +#, fuzzy +#~ msgid "Compiler-enforced scope-based like Rust:" +#~ msgstr "由編譯器強制執行。" + +#, fuzzy +#~ msgid "Enforced by compiler." +#~ msgstr "沒有執行階段負擔。" + +#~ msgid "Cons of Different Memory Management Techniques" +#~ msgstr "不同記憶體管理技巧的缺點" + +#~ msgid "Use-after-free." +#~ msgstr "使用已釋放記憶體。" + +#~ msgid "Double-frees." +#~ msgstr "重複釋放。" + +#~ msgid "Memory leaks." +#~ msgstr "記憶體泄漏。" + +#~ msgid "Garbage collection pauses." +#~ msgstr "垃圾回收機制會暫停。" + +#~ msgid "Destructor delays." +#~ msgstr "解構函式會延遲。" + +#~ msgid "Complex, opt-in by programmer." +#~ msgstr "相當複雜,由程式設計師自行選用。" + +#~ msgid "Potential for use-after-free." +#~ msgstr "可能會使用已釋放記憶體。" + +#~ msgid "Compiler-enforced and scope-based like Rust:" +#~ msgstr "編譯器強制執行的範圍式管理,例如 Rust:" + +#~ msgid "Some upfront complexity." +#~ msgstr "一開始較為複雜。" + +#~ msgid "Can reject valid programs." +#~ msgstr "可能會拒絕有效程式。" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn main() {\n" +#~ " {\n" +#~ " let p = Point(3, 4);\n" +#~ " println!(\"x: {}\", p.0);\n" +#~ " }\n" +#~ " println!(\"y: {}\", p.1);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn main() {\n" +#~ " {\n" +#~ " let p = Point(3, 4);\n" +#~ " println!(\"x: {}\", p.0);\n" +#~ " }\n" +#~ " println!(\"y: {}\", p.1);\n" +#~ "}\n" +#~ "```" + +#~ msgid "A destructor can run here to free up resources." +#~ msgstr "解構函式可在這時執行,用來釋放資源。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let s1: String = String::from(\"Hello!\");\n" +#~ " let s2: String = s1;\n" +#~ " println!(\"s2: {s2}\");\n" +#~ " // println!(\"s1: {s1}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let s1: String = String::from(\"Hello!\");\n" +#~ " let s2: String = s1;\n" +#~ " println!(\"s2: {s2}\");\n" +#~ " // println!(\"s1: {s1}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "The data was _moved_ from `s1` and `s1` is no longer accessible." +#~ msgstr "資料已從 `s1`「移出」,`s1` 無法再供存取。" + +#~ msgid "There is always _exactly_ one variable binding which owns a value." +#~ msgstr "一律「只有」一個變數綁定會擁有值。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let s1: String = String::from(\"Rust\");\n" +#~ " let s2: String = s1;\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let s1: String = String::from(\"Rust\");\n" +#~ " let s2: String = s1;\n" +#~ "}\n" +#~ "```" + +#~ msgid "The heap data from `s1` is reused for `s2`." +#~ msgstr "系統會為 `s2` 重複使用 `s1` 的堆積資料。" + +#~ msgid "" +#~ "When `s1` goes out of scope, nothing happens (it has been moved from)." +#~ msgstr "當 `s1` 超出範圍時,系統不會執行任何動作,因為 `s1` 已移出。" + +#~ msgid "" +#~ "```bob\n" +#~ " Stack Heap\n" +#~ ".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" +#~ ": : : :\n" +#~ ": s1 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+----+ :\n" +#~ ": | ptr | o---+---+-----+-->| R | u | s | t | :\n" +#~ ": | len | 4 | : : +----+----+----+----+ :\n" +#~ ": | capacity | 4 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : `- - - - - - - - - - - - - -'\n" +#~ ": :\n" +#~ "`- - - - - - - - - - - - - -'\n" +#~ "```" +#~ msgstr "" +#~ "```bob\n" +#~ " 堆疊 堆積\n" +#~ ".- - - - - - - - - - - - - -. .- - - - - - - - - - - - - -.\n" +#~ ": : : :\n" +#~ ": s1 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+----+ :\n" +#~ ": | ptr | o---+---+-----+-->| R | u | s | t | :\n" +#~ ": | len | 4 | : : +----+----+----+----+ :\n" +#~ ": | capacity | 4 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : `- - - - - - - - - - - - - -'\n" +#~ ": :\n" +#~ "`- - - - - - - - - - - - - -'\n" +#~ "```" + +#~ msgid "" +#~ "```c++\n" +#~ "std::string s1 = \"Cpp\";\n" +#~ "std::string s2 = s1; // Duplicate the data in s1.\n" +#~ "```" +#~ msgstr "" +#~ "```c++\n" +#~ "std::string s1 = \"Cpp\";\n" +#~ "std::string s2 = s1; // 重複 s1 中的資料。\n" +#~ "```" + +#~ msgid "" +#~ "```bob\n" +#~ " Stack Heap\n" +#~ ".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" +#~ ": : : :\n" +#~ ": s1 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+ :\n" +#~ ": | ptr | o---+---+--+--+-->| C | p | p | :\n" +#~ ": | len | 3 | : : +----+----+----+ :\n" +#~ ": | capacity | 3 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : `- - - - - - - - - - - -'\n" +#~ "`- - - - - - - - - - - - - -'\n" +#~ "```" +#~ msgstr "" +#~ "```bob\n" +#~ " 堆疊 堆積\n" +#~ ".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" +#~ ": : : :\n" +#~ ": s1 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+ :\n" +#~ ": | ptr | o---+---+--+--+-->| C | p | p | :\n" +#~ ": | len | 3 | : : +----+----+----+ :\n" +#~ ": | capacity | 3 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : `- - - - - - - - - - - -'\n" +#~ "`- - - - - - - - - - - - - -'\n" +#~ "```" + +#~ msgid "" +#~ "```bob\n" +#~ " Stack Heap\n" +#~ ".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" +#~ ": : : :\n" +#~ ": s1 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+ :\n" +#~ ": | ptr | o---+---+--+--+-->| C | p | p | :\n" +#~ ": | len | 3 | : : +----+----+----+ :\n" +#~ ": | capacity | 3 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : : :\n" +#~ ": s2 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+ :\n" +#~ ": | ptr | o---+---+-----+-->| C | p | p | :\n" +#~ ": | len | 3 | : : +----+----+----+ :\n" +#~ ": | capacity | 3 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : `- - - - - - - - - - - -'\n" +#~ "`- - - - - - - - - - - - - -'\n" +#~ "```" +#~ msgstr "" +#~ "```bob\n" +#~ " 堆疊 堆積\n" +#~ ".- - - - - - - - - - - - - -. .- - - - - - - - - - - -.\n" +#~ ": : : :\n" +#~ ": s1 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+ :\n" +#~ ": | ptr | o---+---+--+--+-->| C | p | p | :\n" +#~ ": | len | 3 | : : +----+----+----+ :\n" +#~ ": | capacity | 3 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : : :\n" +#~ ": s2 : : :\n" +#~ ": +-----------+-------+ : : +----+----+----+ :\n" +#~ ": | ptr | o---+---+-----+-->| C | p | p | :\n" +#~ ": | len | 3 | : : +----+----+----+ :\n" +#~ ": | capacity | 3 | : : :\n" +#~ ": +-----------+-------+ : : :\n" +#~ ": : `- - - - - - - - - - - -'\n" +#~ "`- - - - - - - - - - - - - -'\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn say_hello(name: String) {\n" +#~ " println!(\"Hello {name}\")\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let name = String::from(\"Alice\");\n" +#~ " say_hello(name);\n" +#~ " // say_hello(name);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn say_hello(name: String) {\n" +#~ " println!(\"Hello {name}\")\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let name = String::from(\"Alice\");\n" +#~ " say_hello(name);\n" +#~ " // say_hello(name);\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let x = 42;\n" +#~ " let y = x;\n" +#~ " println!(\"x: {x}\");\n" +#~ " println!(\"y: {y}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let x = 42;\n" +#~ " let y = x;\n" +#~ " println!(\"x: {x}\");\n" +#~ " println!(\"y: {y}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#[derive(Copy, Clone, Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1 = Point(3, 4);\n" +#~ " let p2 = p1;\n" +#~ " println!(\"p1: {p1:?}\");\n" +#~ " println!(\"p2: {p2:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#[derive(Copy, Clone, Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1 = Point(3, 4);\n" +#~ " let p2 = p1;\n" +#~ " println!(\"p1: {p1:?}\");\n" +#~ " println!(\"p2: {p2:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "If students ask about `derive`, it is sufficient to say that this is a " +#~ "way to generate code in Rust at compile time. In this case the default " +#~ "implementations of `Copy` and `Clone` traits are generated." +#~ msgstr "" +#~ "如有學員問起 `derive`,只需回答這是在 Rust 編譯時間中產生程式碼的方式。在" +#~ "這種情形下,系統會產生 `Copy` 和 `Clone` 特徵的預設實作方式。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn add(p1: &Point, p2: &Point) -> Point {\n" +#~ " Point(p1.0 + p2.0, p1.1 + p2.1)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1 = Point(3, 4);\n" +#~ " let p2 = Point(10, 20);\n" +#~ " let p3 = add(&p1, &p2);\n" +#~ " println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn add(p1: &Point, p2: &Point) -> Point {\n" +#~ " Point(p1.0 + p2.0, p1.1 + p2.1)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1 = Point(3, 4);\n" +#~ " let p2 = Point(10, 20);\n" +#~ " let p3 = add(&p1, &p2);\n" +#~ " println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn add(p1: &Point, p2: &Point) -> Point {\n" +#~ " let p = Point(p1.0 + p2.0, p1.1 + p2.1);\n" +#~ " println!(\"&p.0: {:p}\", &p.0);\n" +#~ " p\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1 = Point(3, 4);\n" +#~ " let p2 = Point(10, 20);\n" +#~ " let p3 = add(&p1, &p2);\n" +#~ " println!(\"&p3.0: {:p}\", &p3.0);\n" +#~ " println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn add(p1: &Point, p2: &Point) -> Point {\n" +#~ " let p = Point(p1.0 + p2.0, p1.1 + p2.1);\n" +#~ " println!(\"&p.0: {:p}\", &p.0);\n" +#~ " p\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1 = Point(3, 4);\n" +#~ " let p2 = Point(10, 20);\n" +#~ " let p3 = add(&p1, &p2);\n" +#~ " println!(\"&p3.0: {:p}\", &p3.0);\n" +#~ " println!(\"{p1:?} + {p2:?} = {p3:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "fn main() {\n" +#~ " let mut a: i32 = 10;\n" +#~ " let b: &i32 = &a;\n" +#~ "\n" +#~ " {\n" +#~ " let c: &mut i32 = &mut a;\n" +#~ " *c = 20;\n" +#~ " }\n" +#~ "\n" +#~ " println!(\"a: {a}\");\n" +#~ " println!(\"b: {b}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "fn main() {\n" +#~ " let mut a: i32 = 10;\n" +#~ " let b: &i32 = &a;\n" +#~ "\n" +#~ " {\n" +#~ " let c: &mut i32 = &mut a;\n" +#~ " *c = 20;\n" +#~ " }\n" +#~ "\n" +#~ " println!(\"a: {a}\");\n" +#~ " println!(\"b: {b}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "A borrowed value has a _lifetime_:" +#~ msgstr "借用的值具有「生命週期」:" + +#~ msgid "" +#~ "The lifetime can be implicit: `add(p1: &Point, p2: &Point) -> Point`." +#~ msgstr "生命週期可以採用隱含方式:`add(p1: &Point, p2: &Point) -> Point`。" + +#~ msgid "Lifetimes can also be explicit: `&'a Point`, `&'document str`." +#~ msgstr "生命週期也可以採用明確方式:`&'a Point`、`&'document str`。" + +#~ msgid "" +#~ "Read `&'a Point` as \"a borrowed `Point` which is valid for at least the " +#~ "lifetime `a`\"." +#~ msgstr "請將 `&'a Point` 讀做「至少對生命週期 `a` 有效的借用 `Point`」。" + +#~ msgid "" +#~ "Lifetimes are always inferred by the compiler: you cannot assign a " +#~ "lifetime yourself." +#~ msgstr "生命週期一律會由編譯器推論:您無法自行指派生命週期。" + +#~ msgid "" +#~ "In addition to borrowing its arguments, a function can return a borrowed " +#~ "value:" +#~ msgstr "除了借用引數,函式也可以傳回借用的值:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" +#~ " if p1.0 < p2.0 { p1 } else { p2 }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1: Point = Point(10, 10);\n" +#~ " let p2: Point = Point(20, 20);\n" +#~ " let p3: &Point = left_most(&p1, &p2);\n" +#~ " println!(\"left-most point: {:?}\", p3);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" +#~ " if p1.0 < p2.0 { p1 } else { p2 }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1: Point = Point(10, 10);\n" +#~ " let p2: Point = Point(20, 20);\n" +#~ " let p3: &Point = left_most(&p1, &p2);\n" +#~ " println!(\"left-most point: {:?}\", p3);\n" +#~ "}\n" +#~ "```" + +#~ msgid "`'a` is a generic parameter, it is inferred by the compiler." +#~ msgstr "`'a` 是由編譯器推論的泛型參數。" + +#~ msgid "Lifetimes start with `'` and `'a` is a typical default name." +#~ msgstr "生命週期的開頭為 `'`,一般預設名稱為 `'a`。" + +#~ msgid "" +#~ "The _at least_ part is important when parameters are in different scopes." +#~ msgstr "如果參數位於不同的範圍,「至少」一詞就至關重要。" + +#~ msgid "" +#~ "Move the declaration of `p2` and `p3` into a new scope (`{ ... }`), " +#~ "resulting in the following code:" +#~ msgstr "將 `p2` 和 `p3` 的宣告移至新範圍 (`{ ... }`),會產生以下程式碼:" + +#~ msgid "" +#~ "```rust,ignore\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" +#~ " if p1.0 < p2.0 { p1 } else { p2 }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1: Point = Point(10, 10);\n" +#~ " let p3: &Point;\n" +#~ " {\n" +#~ " let p2: Point = Point(20, 20);\n" +#~ " p3 = left_most(&p1, &p2);\n" +#~ " }\n" +#~ " println!(\"left-most point: {:?}\", p3);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,ignore\n" +#~ "#[derive(Debug)]\n" +#~ "struct Point(i32, i32);\n" +#~ "\n" +#~ "fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {\n" +#~ " if p1.0 < p2.0 { p1 } else { p2 }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let p1: Point = Point(10, 10);\n" +#~ " let p3: &Point;\n" +#~ " {\n" +#~ " let p2: Point = Point(20, 20);\n" +#~ " p3 = left_most(&p1, &p2);\n" +#~ " }\n" +#~ " println!(\"left-most point: {:?}\", p3);\n" +#~ "}\n" +#~ "```" + +#~ msgid "Note how this does not compile since `p3` outlives `p2`." +#~ msgstr "請注意,這在 `p3` 超越 `p2` 並繼續留存後,就沒有編譯。" + +#~ msgid "" +#~ "Reset the workspace and change the function signature to `fn " +#~ "left_most<'a, 'b>(p1: &'a Point, p2: &'a Point) -> &'b Point`. This will " +#~ "not compile because the relationship between the lifetimes `'a` and `'b` " +#~ "is unclear." +#~ msgstr "" +#~ "重設工作區,並將函式簽章變更為 `fn left_most<'a, 'b>(p1: &'a Point, p2: " +#~ "&'a Point) -> &'b Point`。這不會編譯,因為生命週期 `'a` 和 `'b` 之間的關係" +#~ "不明確。" + +#~ msgid "Another way to explain it:" +#~ msgstr "另一種說明方式:" + +#~ msgid "" +#~ "Two references to two values are borrowed by a function and the function " +#~ "returns another reference." +#~ msgstr "函式會借用兩個值的兩個參照,而函式會傳回另一個參照。" + +#~ msgid "" +#~ "It must have come from one of those two inputs (or from a global " +#~ "variable)." +#~ msgstr "該參照必須來自這兩種輸入來源的其中之一 (或來自全域變數)。" + +#~ msgid "" +#~ "Which one is it? The compiler needs to know, so at the call site the " +#~ "returned reference is not used for longer than a variable from where the " +#~ "reference came from." +#~ msgstr "" +#~ "究竟是哪一個來源?編譯器需要知道來源為何,因此在呼叫點上,所傳回參照的使用" +#~ "時間不會長於來自參照來源的變數。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Highlight<'doc>(&'doc str);\n" +#~ "\n" +#~ "fn erase(text: String) {\n" +#~ " println!(\"Bye {text}!\");\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let text = String::from(\"The quick brown fox jumps over the lazy dog." +#~ "\");\n" +#~ " let fox = Highlight(&text[4..19]);\n" +#~ " let dog = Highlight(&text[35..43]);\n" +#~ " // erase(text);\n" +#~ " println!(\"{fox:?}\");\n" +#~ " println!(\"{dog:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#[derive(Debug)]\n" +#~ "struct Highlight<'doc>(&'doc str);\n" +#~ "\n" +#~ "fn erase(text: String) {\n" +#~ " println!(\"Bye {text}!\");\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let text = String::from(\"The quick brown fox jumps over the lazy dog." +#~ "\");\n" +#~ " let fox = Highlight(&text[4..19]);\n" +#~ " let dog = Highlight(&text[35..43]);\n" +#~ " // erase(text);\n" +#~ " println!(\"{fox:?}\");\n" +#~ " println!(\"{dog:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "Day 1: Afternoon Exercises" +#~ msgstr "第 1 天:下午練習" + +#~ msgid "We will look at two things:" +#~ msgstr "我們將著重在以下兩點:" + +#~ msgid "" +#~ "We will learn much more about structs and the `Vec` type tomorrow. For " +#~ "now, you just need to know part of its API:" +#~ msgstr "" +#~ "明天我們會進一步講解結構體和 `Vec` 型別。現階段,您只需要瞭解相關 API " +#~ "的部分內容:" + +#~ msgid "[Solution](solutions-afternoon.md#designing-a-library)" +#~ msgstr "[解決方案](solutions-afternoon.md#designing-a-library)" + +#~ msgid "" +#~ "The ownership model of Rust affects many APIs. An example of this is the " +#~ "[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " +#~ "[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator." +#~ "html) traits." +#~ msgstr "" +#~ "Rust 的擁有權模型會影響許多 API。[`Iterator`](https://doc.rust-lang.org/" +#~ "std/iter/trait.Iterator.html) 和 [`IntoIterator`](https://doc.rust-lang." +#~ "org/std/iter/trait.IntoIterator.html) 特徵就是一例。" + +#~ msgid "" +#~ "Traits are like interfaces: they describe behavior (methods) for a type. " +#~ "The `Iterator` trait simply says that you can call `next` until you get " +#~ "`None` back:" +#~ msgstr "" +#~ "特徵就像介面一樣,可以說明型別的行為 (方法)。`Iterator` 特徵就是指您可以呼" +#~ "叫 `next`,直到取回 `None` 為止:" + +#~ msgid "You use this trait like this:" +#~ msgstr "您可以像下方這樣使用這個特徵:" + +#~ msgid "What is the type returned by the iterator? Test your answer here:" +#~ msgstr "如要瞭解疊代器傳回的型別為何,不妨在這裡測試答案:" + +#~ msgid "Why is this type used?" +#~ msgstr "思考一下,為什麼會使用這種型別?" + +#~ msgid "Like before, what is the type returned by the iterator?" +#~ msgstr "和先前一樣,思考疊代器傳回的型別為何。" + +#~ msgid "" +#~ "Now that we know both `Iterator` and `IntoIterator`, we can build `for` " +#~ "loops. They call `into_iter()` on an expression and iterates over the " +#~ "resulting iterator:" +#~ msgstr "" +#~ "現在我們已瞭解 `Iterator` 和 `IntoIterator`,可以建構 `for` 迴圈了。這會在" +#~ "運算式上呼叫 `into_iter()`,並對產生的疊代器進行疊代:" + +#, fuzzy +#~ msgid "Structs, enums, methods." +#~ msgstr "結構體和方法。" + +#~ msgid "" +#~ "Control flow constructs: `if`, `if let`, `while`, `while let`, `break`, " +#~ "and `continue`." +#~ msgstr "" +#~ "控制流程結構:`if`、`if let`、`while`、`while let`、`break` 和 " +#~ "`continue`。" + +#~ msgid "" +#~ "The Standard Library: `String`, `Option` and `Result`, `Vec`, `HashMap`, " +#~ "`Rc` and `Arc`." +#~ msgstr "" +#~ "標準程式庫:`String`、`Option` 和 `Result`、`Vec`、`HashMap`、`Rc` 和 " +#~ "`Arc`。" + +#~ msgid "Modules: visibility, paths, and filesystem hierarchy." +#~ msgstr "模組:瀏覽權限、路徑和檔案系統階層。" + +#~ msgid "" +#~ "Methods are defined in an `impl` block, which we will see in following " +#~ "slides." +#~ msgstr "方法會在 `impl` 區塊中定義,我們將於接下來的投影片說明這點。" + +#~ msgid "" +#~ "The `new` function could be written using `Self` as a type, as it is " +#~ "interchangeable with the struct type name" +#~ msgstr "" +#~ "您可以將 `Self` 用做型別來編寫 `new` 函式,因為它可和結構體型別名稱互通。" + +#~ msgid "" +#~ "Implement the `Default` trait for the struct. Define some fields and use " +#~ "the default values for the other fields." +#~ msgstr "" +#~ "實作結構體的 `Default` 特徵。請定義部分欄位,並針對其他欄位使用預設值。" + +#~ msgid "Methods are defined in the `impl` block." +#~ msgstr "方法會在 `impl` 區塊中定義。" + +#~ msgid "" +#~ "Use struct update syntax to define a new structure using `peter`. Note " +#~ "that the variable `peter` will no longer be accessible afterwards." +#~ msgstr "" +#~ "使用結構體更新語法,利用 `peter` 定義新結構。請注意,`peter` 這個變數之後" +#~ "將再也無法存取。" + +#~ msgid "" +#~ "Use `{:#?}` when printing structs to request the `Debug` representation." +#~ msgstr "輸出結構體時,請使用 `{:#?}` 提出 `Debug` 表示法要求。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn generate_random_number() -> i32 {\n" +#~ " // Implementation based on https://xkcd.com/221/\n" +#~ " 4 // Chosen by fair dice roll. Guaranteed to be random.\n" +#~ "}\n" +#~ "\n" +#~ "#[derive(Debug)]\n" +#~ "enum CoinFlip {\n" +#~ " Heads,\n" +#~ " Tails,\n" +#~ "}\n" +#~ "\n" +#~ "fn flip_coin() -> CoinFlip {\n" +#~ " let random_number = generate_random_number();\n" +#~ " if random_number % 2 == 0 {\n" +#~ " return CoinFlip::Heads;\n" +#~ " } else {\n" +#~ " return CoinFlip::Tails;\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " println!(\"You got: {:?}\", flip_coin());\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn generate_random_number() -> i32 {\n" +#~ " // Implementation based on https://xkcd.com/221/\n" +#~ " 4 // Chosen by fair dice roll. Guaranteed to be random.\n" +#~ "}\n" +#~ "\n" +#~ "#[derive(Debug)]\n" +#~ "enum CoinFlip {\n" +#~ " Heads,\n" +#~ " Tails,\n" +#~ "}\n" +#~ "\n" +#~ "fn flip_coin() -> CoinFlip {\n" +#~ " let random_number = generate_random_number();\n" +#~ " if random_number % 2 == 0 {\n" +#~ " return CoinFlip::Heads;\n" +#~ " } else {\n" +#~ " return CoinFlip::Tails;\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " println!(\"You got: {:?}\", flip_coin());\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "This page offers an enum type `CoinFlip` with two variants `Heads` and " +#~ "`Tail`. You might note the namespace when using variants." +#~ msgstr "" +#~ "本頁面提供列舉類別 `CoinFlip`,以及 `Heads` 和 `Tail` 這兩個變體。您可以在" +#~ "使用變體時記下命名空間。" + +#~ msgid "In both, associated functions are defined within an `impl` block." +#~ msgstr "無論使用何者,相關函式都會在 `impl` 區塊中定義。" + +#~ msgid "" +#~ "You can define richer enums where the variants carry data. You can then " +#~ "use the `match` statement to extract the data from each variant:" +#~ msgstr "" +#~ "您可以定義更豐富的列舉,讓列舉的變體攜帶資料。接著,您可以使用 `match` 陳" +#~ "述式,從各個變體擷取資料:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "enum WebEvent {\n" +#~ " PageLoad, // Variant without payload\n" +#~ " KeyPress(char), // Tuple struct variant\n" +#~ " Click { x: i64, y: i64 }, // Full struct variant\n" +#~ "}\n" +#~ "\n" +#~ "#[rustfmt::skip]\n" +#~ "fn inspect(event: WebEvent) {\n" +#~ " match event {\n" +#~ " WebEvent::PageLoad => println!(\"page loaded\"),\n" +#~ " WebEvent::KeyPress(c) => println!(\"pressed '{c}'\"),\n" +#~ " WebEvent::Click { x, y } => println!(\"clicked at x={x}, " +#~ "y={y}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let load = WebEvent::PageLoad;\n" +#~ " let press = WebEvent::KeyPress('x');\n" +#~ " let click = WebEvent::Click { x: 20, y: 80 };\n" +#~ "\n" +#~ " inspect(load);\n" +#~ " inspect(press);\n" +#~ " inspect(click);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "enum WebEvent {\n" +#~ " PageLoad, // Variant without payload\n" +#~ " KeyPress(char), // Tuple struct variant\n" +#~ " Click { x: i64, y: i64 }, // Full struct variant\n" +#~ "}\n" +#~ "\n" +#~ "#[rustfmt::skip]\n" +#~ "fn inspect(event: WebEvent) {\n" +#~ " match event {\n" +#~ " WebEvent::PageLoad => println!(\"page loaded\"),\n" +#~ " WebEvent::KeyPress(c) => println!(\"pressed '{c}'\"),\n" +#~ " WebEvent::Click { x, y } => println!(\"clicked at x={x}, " +#~ "y={y}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let load = WebEvent::PageLoad;\n" +#~ " let press = WebEvent::KeyPress('x');\n" +#~ " let click = WebEvent::Click { x: 20, y: 80 };\n" +#~ "\n" +#~ " inspect(load);\n" +#~ " inspect(press);\n" +#~ " inspect(click);\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "The expression is matched against the patterns from top to bottom. There " +#~ "is no fall-through like in C or C++." +#~ msgstr "" +#~ "系統會從上到下將運算式與模式進行配對。在 Rust 中,不會像在 C 或 C++ 中一樣" +#~ "出現貫穿 (fall-through) 情形。" + +#~ msgid "" +#~ "The match expression has a value. The value is the last expression in the " +#~ "match arm which was executed." +#~ msgstr "配對運算式具有值。此值是系統執行的配對分支中的最後一個運算式。" + +#~ msgid "" +#~ "Starting from the top we look for what pattern matches the value then run " +#~ "the code following the arrow. Once we find a match, we stop. " +#~ msgstr "" +#~ "我們會從上方開始尋找符合該值的模式,然後執行箭頭後方的程式碼。一旦發現相符" +#~ "項目,就會停止。" + +#~ msgid "`match` inspects a hidden discriminant field in the `enum`." +#~ msgstr "`match` 會檢查 `enum` 中隱藏的判別值欄位。" + +#~ msgid "" +#~ "It is possible to retrieve the discriminant by calling `std::mem::" +#~ "discriminant()`" +#~ msgstr "只要呼叫 `std::mem::discriminant()`,就有可能擷取該判別值。\\`" + +#~ msgid "" +#~ "This is useful, for example, if implementing `PartialEq` for structs " +#~ "where comparing field values doesn't affect equality." +#~ msgstr "" +#~ "舉例來說,如果在為結構體實作 `PartialEq` 時,比較欄位值不會對相等性造成影" +#~ "響,這種做法就很實用。" + +#~ msgid "" +#~ "`WebEvent::Click { ... }` is not exactly the same as `WebEvent::" +#~ "Click(Click)` with a top level `struct Click { ... }`. The inlined " +#~ "version cannot implement traits, for example." +#~ msgstr "" +#~ "`WebEvent::Click { ... }` 與具有頂層 `struct Click { ... }` 的 `WebEvent::" +#~ "Click(Click)` 並非完全相同。舉例來說,內嵌版本無法實作特徵。" + +#~ msgid "" +#~ "Rust enums are packed tightly, taking constraints due to alignment into " +#~ "account:" +#~ msgstr "Rust 列舉會緊密封裝,並考量因對齊而造成的限制:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::mem::{align_of, size_of};\n" +#~ "\n" +#~ "macro_rules! dbg_size {\n" +#~ " ($t:ty) => {\n" +#~ " println!(\"{}: size {} bytes, align: {} bytes\",\n" +#~ " stringify!($t), size_of::<$t>(), align_of::<$t>());\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "enum Foo {\n" +#~ " A,\n" +#~ " B,\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " dbg_size!(Foo);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::mem::{align_of, size_of};\n" +#~ "\n" +#~ "macro_rules! dbg_size {\n" +#~ " ($t:ty) => {\n" +#~ " println!(\"{}: size {} bytes, align: {} bytes\",\n" +#~ " stringify!($t), size_of::<$t>(), align_of::<$t>());\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "enum Foo {\n" +#~ " A,\n" +#~ " B,\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " dbg_size!(Foo);\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "Internally Rust is using a field (discriminant) to keep track of the enum " +#~ "variant." +#~ msgstr "在內部,Rust 會使用欄位 (判別值) 追蹤列舉變體。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#[repr(u32)]\n" +#~ "enum Bar {\n" +#~ " A, // 0\n" +#~ " B = 10000,\n" +#~ " C, // 10001\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " println!(\"A: {}\", Bar::A as u32);\n" +#~ " println!(\"B: {}\", Bar::B as u32);\n" +#~ " println!(\"C: {}\", Bar::C as u32);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#[repr(u32)]\n" +#~ "enum Bar {\n" +#~ " A, // 0\n" +#~ " B = 10000,\n" +#~ " C, // 10001\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " println!(\"A: {}\", Bar::A as u32);\n" +#~ " println!(\"B: {}\", Bar::B as u32);\n" +#~ " println!(\"C: {}\", Bar::C as u32);\n" +#~ "}\n" +#~ "```" + +#~ msgid "Try out other types such as" +#~ msgstr "請嘗試其他型別,例如以下項目:" + +#~ msgid "`dbg_size!(bool)`: size 1 bytes, align: 1 bytes," +#~ msgstr "`dbg_size!(bool)`:大小為 1 個位元組,對齊:1 個位元組。" + +#~ msgid "" +#~ "`dbg_size!(Option)`: size 1 bytes, align: 1 bytes (niche " +#~ "optimization, see below)," +#~ msgstr "" +#~ "`dbg_size!(Option)`:大小為 1 個位元組,對齊:1 個位元組 (區位最佳" +#~ "化,請見下文)。" + +#~ msgid "" +#~ "`dbg_size!(&i32)`: size 8 bytes, align: 8 bytes (on a 64-bit machine)," +#~ msgstr "" +#~ "`dbg_size!(&i32)`:大小為 8 個位元組,對齊:8 個位元組 (在 64 位元機器" +#~ "上)。" + +#~ msgid "" +#~ "`dbg_size!(Option<&i32>)`: size 8 bytes, align: 8 bytes (null pointer " +#~ "optimization, see below)." +#~ msgstr "" +#~ "`dbg_size!(Option<&i32>)`:大小為 8 個位元組,對齊:8 個位元組 (空值指標最" +#~ "佳化,請見下文)。" + +#~ msgid "" +#~ "Niche optimization: Rust will merge use unused bit patterns for the enum " +#~ "discriminant." +#~ msgstr "區位最佳化:Rust 會為列舉判別值合併未使用的位元模式。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::mem::transmute;\n" +#~ "\n" +#~ "macro_rules! dbg_bits {\n" +#~ " ($e:expr, $bit_type:ty) => {\n" +#~ " println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " +#~ "$bit_type>($e));\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" +#~ " // representation of types.\n" +#~ " unsafe {\n" +#~ " println!(\"Bitwise representation of bool\");\n" +#~ " dbg_bits!(false, u8);\n" +#~ " dbg_bits!(true, u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of Option\");\n" +#~ " dbg_bits!(None::, u8);\n" +#~ " dbg_bits!(Some(false), u8);\n" +#~ " dbg_bits!(Some(true), u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of Option>\");\n" +#~ " dbg_bits!(Some(Some(false)), u8);\n" +#~ " dbg_bits!(Some(Some(true)), u8);\n" +#~ " dbg_bits!(Some(None::), u8);\n" +#~ " dbg_bits!(None::>, u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of Option<&i32>\");\n" +#~ " dbg_bits!(None::<&i32>, usize);\n" +#~ " dbg_bits!(Some(&0i32), usize);\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::mem::transmute;\n" +#~ "\n" +#~ "macro_rules! dbg_bits {\n" +#~ " ($e:expr, $bit_type:ty) => {\n" +#~ " println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " +#~ "$bit_type>($e));\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" +#~ " // representation of types.\n" +#~ " unsafe {\n" +#~ " println!(\"Bitwise representation of bool\");\n" +#~ " dbg_bits!(false, u8);\n" +#~ " dbg_bits!(true, u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of Option\");\n" +#~ " dbg_bits!(None::, u8);\n" +#~ " dbg_bits!(Some(false), u8);\n" +#~ " dbg_bits!(Some(true), u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of Option>\");\n" +#~ " dbg_bits!(Some(Some(false)), u8);\n" +#~ " dbg_bits!(Some(Some(true)), u8);\n" +#~ " dbg_bits!(Some(None::), u8);\n" +#~ " dbg_bits!(None::>, u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of Option<&i32>\");\n" +#~ " dbg_bits!(None::<&i32>, usize);\n" +#~ " dbg_bits!(Some(&0i32), usize);\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "More complex example if you want to discuss what happens when we chain " +#~ "more than 256 `Option`s together." +#~ msgstr "" +#~ "如果想討論將超過 256 個 `Option` 鏈結在一起的情況,可以使用下列更複雜的範" +#~ "例。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "#![recursion_limit = \"1000\"]\n" +#~ "\n" +#~ "use std::mem::transmute;\n" +#~ "\n" +#~ "macro_rules! dbg_bits {\n" +#~ " ($e:expr, $bit_type:ty) => {\n" +#~ " println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " +#~ "$bit_type>($e));\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "// Macro to wrap a value in 2^n Some() where n is the number of \"@\" " +#~ "signs.\n" +#~ "// Increasing the recursion limit is required to evaluate this macro.\n" +#~ "macro_rules! many_options {\n" +#~ " ($value:expr) => { Some($value) };\n" +#~ " ($value:expr, @) => {\n" +#~ " Some(Some($value))\n" +#~ " };\n" +#~ " ($value:expr, @ $($more:tt)+) => {\n" +#~ " many_options!(many_options!($value, $($more)+), $($more)+)\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" +#~ " // representation of types.\n" +#~ " unsafe {\n" +#~ " assert_eq!(many_options!(false), Some(false));\n" +#~ " assert_eq!(many_options!(false, @), Some(Some(false)));\n" +#~ " assert_eq!(many_options!(false, @@), " +#~ "Some(Some(Some(Some(false)))));\n" +#~ "\n" +#~ " println!(\"Bitwise representation of a chain of 128 Option's." +#~ "\");\n" +#~ " dbg_bits!(many_options!(false, @@@@@@@), u8);\n" +#~ " dbg_bits!(many_options!(true, @@@@@@@), u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of a chain of 256 Option's." +#~ "\");\n" +#~ " dbg_bits!(many_options!(false, @@@@@@@@), u16);\n" +#~ " dbg_bits!(many_options!(true, @@@@@@@@), u16);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of a chain of 257 Option's." +#~ "\");\n" +#~ " dbg_bits!(many_options!(Some(false), @@@@@@@@), u16);\n" +#~ " dbg_bits!(many_options!(Some(true), @@@@@@@@), u16);\n" +#~ " dbg_bits!(many_options!(None::, @@@@@@@@), u16);\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "#![recursion_limit = \"1000\"]\n" +#~ "\n" +#~ "use std::mem::transmute;\n" +#~ "\n" +#~ "macro_rules! dbg_bits {\n" +#~ " ($e:expr, $bit_type:ty) => {\n" +#~ " println!(\"- {}: {:#x}\", stringify!($e), transmute::<_, " +#~ "$bit_type>($e));\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "// 在 2^n Some() 中包裝值的巨集,n 為「@」符號的數字。\n" +#~ "// 評估此巨集時,必須提高遞迴限制。\n" +#~ "macro_rules! many_options {\n" +#~ " ($value:expr) => { Some($value) };\n" +#~ " ($value:expr, @) => {\n" +#~ " Some(Some($value))\n" +#~ " };\n" +#~ " ($value:expr, @ $($more:tt)+) => {\n" +#~ " many_options!(many_options!($value, $($more)+), $($more)+)\n" +#~ " };\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " // TOTALLY UNSAFE. Rust provides no guarantees about the bitwise\n" +#~ " // representation of types.\n" +#~ " unsafe {\n" +#~ " assert_eq!(many_options!(false), Some(false));\n" +#~ " assert_eq!(many_options!(false, @), Some(Some(false)));\n" +#~ " assert_eq!(many_options!(false, @@), " +#~ "Some(Some(Some(Some(false)))));\n" +#~ "\n" +#~ " println!(\"Bitwise representation of a chain of 128 Option's." +#~ "\");\n" +#~ " dbg_bits!(many_options!(false, @@@@@@@), u8);\n" +#~ " dbg_bits!(many_options!(true, @@@@@@@), u8);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of a chain of 256 Option's." +#~ "\");\n" +#~ " dbg_bits!(many_options!(false, @@@@@@@@), u16);\n" +#~ " dbg_bits!(many_options!(true, @@@@@@@@), u16);\n" +#~ "\n" +#~ " println!(\"Bitwise representation of a chain of 257 Option's." +#~ "\");\n" +#~ " dbg_bits!(many_options!(Some(false), @@@@@@@@), u16);\n" +#~ " dbg_bits!(many_options!(Some(true), @@@@@@@@), u16);\n" +#~ " dbg_bits!(many_options!(None::, @@@@@@@@), u16);\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "We describe the distinction between method receivers next." +#~ msgstr "接下來我們將說明方法接收器之間的差異。" + +#~ msgid "" +#~ "Consider emphasizing \"shared and immutable\" and \"unique and mutable\". " +#~ "These constraints always come together in Rust due to borrow checker " +#~ "rules, and `self` is no exception. It isn't possible to reference a " +#~ "struct from multiple locations and call a mutating (`&mut self`) method " +#~ "on it." +#~ msgstr "" +#~ "建議您強調「共用且不可變動」,以及「不重複且可變動」這兩個概念。由於借用檢" +#~ "查器規則的關係,這些限制在 Rust 中一律會一起出現,而 `self` 也不例外。您無" +#~ "法從多個位置參照結構體,並對其呼叫變異 (`&mut self`) 方法。" + +#~ msgid "All four methods here use a different method receiver." +#~ msgstr "這裡的四個方法都使用不同的方法接收器。" + +#~ msgid "" +#~ "You can point out how that changes what the function can do with the " +#~ "variable values and if/how it can be used again in `main`." +#~ msgstr "" +#~ "您可以指出這會如何變更函式能對變數值執行的動作,以及可否/如何在 `main` 中" +#~ "再次使用該函式。" + +#~ msgid "" +#~ "You can showcase the error that appears when trying to call `finish` " +#~ "twice." +#~ msgstr "您可以演示嘗試呼叫 `finish` 兩次時會出現什麼錯誤。" + +#~ msgid "" +#~ "Note that although the method receivers are different, the non-static " +#~ "functions are called the same way in the main body. Rust enables " +#~ "automatic referencing and dereferencing when calling methods. Rust " +#~ "automatically adds in the `&`, `*`, `muts` so that that object matches " +#~ "the method signature." +#~ msgstr "" +#~ "請注意,雖然方法接收器不同,但主體中非靜態函式的呼叫方式相同。Rust 會在呼" +#~ "叫方法時啟用自動參照和取消參照功能,並自動加入 `&`、`*`、`muts`,讓該物件" +#~ "與方法簽章相符。" + +#~ msgid "" +#~ "You might point out that `print_laps` is using a vector that is iterated " +#~ "over. We describe vectors in more detail in the afternoon. " +#~ msgstr "" +#~ "您或許可以指出 `print_laps` 使用了不斷疊代的向量。我們會在下午詳細介紹向" +#~ "量。" + +#~ msgid "The `_` pattern is a wildcard pattern which matches any value." +#~ msgstr "`_` 模式是可與任何值配對的萬用字元模式。" + +#~ msgid "" +#~ "It can be useful to show how binding works, by for instance replacing a " +#~ "wildcard character with a variable, or removing the quotes around `q`." +#~ msgstr "" +#~ "示範綁定的運作方式可能會很有幫助,例如您可以將萬用字元取代為變數,或是移" +#~ "除 `q` 前後的引號。" + +#~ msgid "You can demonstrate matching on a reference." +#~ msgstr "您可以在參照項目上示範如何配對。" + +#~ msgid "" +#~ "This might be a good time to bring up the concept of irrefutable " +#~ "patterns, as the term can show up in error messages." +#~ msgstr "" +#~ "這時候可能很適合提到「不可反駁的模式」這個概念,因為這個詞可能會出現在錯誤" +#~ "消息中。" + +#~ msgid "You can also destructure `structs`:" +#~ msgstr "您也可以解構 `struct`:" + +#~ msgid "" +#~ "You can destructure arrays, tuples, and slices by matching on their " +#~ "elements:" +#~ msgstr "您可以在陣列、元組和切片的元素上配對,藉此解構陣列、元組和切片:" + +#~ msgid "" +#~ "Destructuring of slices of unknown length also works with patterns of " +#~ "fixed length." +#~ msgstr "您可以解構未知長度的切片,同樣的方法也適用於固定長度的模式。" + +#~ msgid "Create a new pattern using `_` to represent an element. " +#~ msgstr "建立使用 `_` 來代表元素的新模式。" + +#~ msgid "Add more values to the array." +#~ msgstr "在陣列中加入更多值。" + +#~ msgid "" +#~ "Point out that how `..` will expand to account for different number of " +#~ "elements." +#~ msgstr "向學員指出為了因應不同元素數量的情況,`..` 會如何展開。" + +#~ msgid "" +#~ "Show matching against the tail with patterns `[.., b]` and `[a@..,b]`" +#~ msgstr "向學員說明與模式 (`[.., b]` 和 `[a@..,b]`) 末端的配對情形。" + +#~ msgid "" +#~ "When matching, you can add a _guard_ to a pattern. This is an arbitrary " +#~ "Boolean expression which will be executed if the pattern matches:" +#~ msgstr "" +#~ "配對時,您可以為模式新增「守衛」。這是任意的布林運算式,會在模式配對成功時" +#~ "執行:" + +#~ msgid "" +#~ "You can use the variables defined in the pattern in your if expression." +#~ msgstr "您可以在 if 運算式中使用模式內定義的變數。" + +#~ msgid "Day 2: Morning Exercises" +#~ msgstr "第 2 天:上午練習" + +#~ msgid "We will look at implementing methods in two contexts:" +#~ msgstr "我們會探討如何在以下兩種情況下實作方法:" + +#~ msgid "Polygon Struct" +#~ msgstr "多邊形結構體" + +#~ msgid "" +#~ "We will create a `Polygon` struct which contain some points. Copy the " +#~ "code below to and fill in the missing " +#~ "methods to make the tests pass:" +#~ msgstr "" +#~ "我們會建立一個包含某幾個點的 `Polygon` 結構體。請將下方程式碼複製到 " +#~ ",並填入缺少的方法,設法通過測試:" + +#~ msgid "" +#~ "Since the method signatures are missing from the problem statements, the " +#~ "key part of the exercise is to specify those correctly. You don't have to " +#~ "modify the tests." +#~ msgstr "" +#~ "由於問題陳述式缺少方法簽章,因此練習的關鍵部分就是正確指定這些簽章。您不需" +#~ "要修改測試。" + +#~ msgid "Other interesting parts of the exercise:" +#~ msgstr "練習中的其他有趣部分如下:" + +#~ msgid "" +#~ "Derive a `Copy` trait for some structs, as in tests the methods sometimes " +#~ "don't borrow their arguments." +#~ msgstr "" +#~ "針對部分結構體衍生 `Copy` 特徵,因為在測試中,方法有時不會借用其引數。" + +#~ msgid "" +#~ "Discover that `Add` trait must be implemented for two objects to be " +#~ "addable via \"+\". Note that we do not discuss generics until Day 3." +#~ msgstr "" +#~ "發現必須實作 `Add` 特徵才能透過「+」新增兩個物件。請注意,我們在第 3 天以" +#~ "前不會討論泛型。" + +#~ msgid "" +#~ "As we have seen, `if` is an expression in Rust. It is used to " +#~ "conditionally evaluate one of two blocks, but the blocks can have a value " +#~ "which then becomes the value of the `if` expression. Other control flow " +#~ "expressions work similarly in Rust." +#~ msgstr "" +#~ "如同我們所見,`if` 是 Rust 中的一種表達式。它可以用來根據條件執行兩個區塊" +#~ "之中的一個,而區塊的執行結果可以進一步轉變成 `if` 表達式的賦值。其他控制流" +#~ "程表達式在 Rust 中也有類似的用法。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let x = {\n" +#~ " let y = 10;\n" +#~ " println!(\"y: {y}\");\n" +#~ " let z = {\n" +#~ " let w = {\n" +#~ " 3 + 4\n" +#~ " };\n" +#~ " println!(\"w: {w}\");\n" +#~ " y * w\n" +#~ " };\n" +#~ " println!(\"z: {z}\");\n" +#~ " z - y\n" +#~ " };\n" +#~ " println!(\"x: {x}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let x = {\n" +#~ " let y = 10;\n" +#~ " println!(\"y: {y}\");\n" +#~ " let z = {\n" +#~ " let w = {\n" +#~ " 3 + 4\n" +#~ " };\n" +#~ " println!(\"w: {w}\");\n" +#~ " y * w\n" +#~ " };\n" +#~ " println!(\"z: {z}\");\n" +#~ " z - y\n" +#~ " };\n" +#~ " println!(\"x: {x}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "The same rule is used for functions: the value of the function body is " +#~ "the return value:" +#~ msgstr "同樣的規則也適用於函式:函式的數值即為函式本體的回傳值:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn double(x: i32) -> i32 {\n" +#~ " x + x\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " println!(\"doubled: {}\", double(7));\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn double(x: i32) -> i32 {\n" +#~ " x + x\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " println!(\"doubled: {}\", double(7));\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "The point of this slide is to show that blocks have a type and value in " +#~ "Rust. " +#~ msgstr "這張投影片所表達的重點在於 Rust 中的區塊具有一個數值以及一個型別。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " if x % 2 == 0 {\n" +#~ " x = x / 2;\n" +#~ " } else {\n" +#~ " x = 3 * x + 1;\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " if x % 2 == 0 {\n" +#~ " x = x / 2;\n" +#~ " } else {\n" +#~ " x = 3 * x + 1;\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " x = if x % 2 == 0 {\n" +#~ " x / 2\n" +#~ " } else {\n" +#~ " 3 * x + 1\n" +#~ " };\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " x = if x % 2 == 0 {\n" +#~ " x / 2\n" +#~ " } else {\n" +#~ " 3 * x + 1\n" +#~ " };\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let arg = std::env::args().next();\n" +#~ " if let Some(value) = arg {\n" +#~ " println!(\"Program name: {value}\");\n" +#~ " } else {\n" +#~ " println!(\"Missing name?\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let arg = std::env::args().next();\n" +#~ " if let Some(value) = arg {\n" +#~ " println!(\"Program name: {value}\");\n" +#~ " } else {\n" +#~ " println!(\"Missing name?\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "`if let` can be more concise than `match`, e.g., when only one case is " +#~ "interesting. In contrast, `match` requires all branches to be covered." +#~ msgstr "" +#~ "`if let` 可以比 `match` 更為精簡,例如只有一個有趣案例時。相對地,`match` " +#~ "必須涵蓋所有分支。" + +#~ msgid "" +#~ "Since 1.65, a similar [let-else](https://doc.rust-lang.org/rust-by-" +#~ "example/flow_control/let_else.html) construct allows to do a " +#~ "destructuring assignment, or if it fails, have a non-returning block " +#~ "branch (panic/return/break/continue):" +#~ msgstr "" +#~ "自 1.65 版起,類似的 [let-else](https://doc.rust-lang.org/rust-by-example/" +#~ "flow_control/let_else.html) 結構可以解構指派項目,或在失敗時具有不會傳回的" +#~ "區塊分支 (panic/return/break/continue):" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " println!(\"{:?}\", second_word_to_upper(\"foo bar\"));\n" +#~ "}\n" +#~ " \n" +#~ "fn second_word_to_upper(s: &str) -> Option {\n" +#~ " let mut it = s.split(' ');\n" +#~ " let (Some(_), Some(item)) = (it.next(), it.next()) else {\n" +#~ " return None;\n" +#~ " };\n" +#~ " Some(item.to_uppercase())\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " println!(\"{:?}\", second_word_to_upper(\"foo bar\"));\n" +#~ "}\n" +#~ " \n" +#~ "fn second_word_to_upper(s: &str) -> Option {\n" +#~ " let mut it = s.split(' ');\n" +#~ " let (Some(_), Some(item)) = (it.next(), it.next()) else {\n" +#~ " return None;\n" +#~ " };\n" +#~ " Some(item.to_uppercase())\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " while x != 1 {\n" +#~ " x = if x % 2 == 0 {\n" +#~ " x / 2\n" +#~ " } else {\n" +#~ " 3 * x + 1\n" +#~ " };\n" +#~ " }\n" +#~ " println!(\"Final x: {x}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " while x != 1 {\n" +#~ " x = if x % 2 == 0 {\n" +#~ " x / 2\n" +#~ " } else {\n" +#~ " 3 * x + 1\n" +#~ " };\n" +#~ " }\n" +#~ " println!(\"Final x: {x}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " let mut iter = v.into_iter();\n" +#~ "\n" +#~ " while let Some(x) = iter.next() {\n" +#~ " println!(\"x: {x}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " let mut iter = v.into_iter();\n" +#~ "\n" +#~ " while let Some(x) = iter.next() {\n" +#~ " println!(\"x: {x}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "`for` loops" +#~ msgstr "`for` 迴圈" + +#~ msgid "" +#~ "The [`for` loop](https://doc.rust-lang.org/std/keyword.for.html) is " +#~ "closely related to the [`while let` loop](while-let-expression.md). It " +#~ "will automatically call `into_iter()` on the expression and then iterate " +#~ "over it:" +#~ msgstr "" +#~ "[`for` 迴圈](https://doc.rust-lang.org/std/keyword.for.html)與 [`while " +#~ "let` 迴圈](while-let-expression.md)密切相關,會自動在運算式上呼叫 " +#~ "`into_iter()`,然後對其進行疊代:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ "\n" +#~ " for x in v {\n" +#~ " println!(\"x: {x}\");\n" +#~ " }\n" +#~ " \n" +#~ " for i in (0..10).step_by(2) {\n" +#~ " println!(\"i: {i}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ "\n" +#~ " for x in v {\n" +#~ " println!(\"x: {x}\");\n" +#~ " }\n" +#~ " \n" +#~ " for i in (0..10).step_by(2) {\n" +#~ " println!(\"i: {i}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "You can use `break` and `continue` here as usual." +#~ msgstr "您可以照常使用 `break` 和 `continue`。" + +#~ msgid "Index iteration is not a special syntax in Rust for just that case." +#~ msgstr "在 Rust 中,索引疊代不是只適用於該情況的特殊語法。" + +#~ msgid "`(0..10)` is a range that implements an `Iterator` trait. " +#~ msgstr "`(0..10)` 是實作 `Iterator` 特徵的範圍。" + +#~ msgid "" +#~ "`step_by` is a method that returns another `Iterator` that skips every " +#~ "other element. " +#~ msgstr "`step_by` 這個方法會傳回另一個略過其他所有元素的 `Iterator`。" + +#~ msgid "" +#~ "Modify the elements in the vector and explain the compiler errors. Change " +#~ "vector `v` to be mutable and the for loop to `for x in v.iter_mut()`." +#~ msgstr "" +#~ "請修改向量中的元素,並說明編譯器錯誤。將向量 `v` 變更為可變動項,並將 for " +#~ "迴圈變更為 `for x in v.iter_mut()`。" + +#~ msgid "`loop` expressions" +#~ msgstr "`loop` 運算式" + +#~ msgid "" +#~ "Finally, there is a [`loop` keyword](https://doc.rust-lang.org/reference/" +#~ "expressions/loop-expr.html#infinite-loops) which creates an endless loop." +#~ msgstr "" +#~ "最後,有一個 [`loop` 關鍵字](https://doc.rust-lang.org/reference/" +#~ "expressions/loop-expr.html#infinite-loops)會建立無限迴圈。" + +#~ msgid "Here you must either `break` or `return` to stop the loop:" +#~ msgstr "這時您必須執行 `break` 或 `return` 來停止迴圈:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " loop {\n" +#~ " x = if x % 2 == 0 {\n" +#~ " x / 2\n" +#~ " } else {\n" +#~ " 3 * x + 1\n" +#~ " };\n" +#~ " if x == 1 {\n" +#~ " break;\n" +#~ " }\n" +#~ " }\n" +#~ " println!(\"Final x: {x}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let mut x = 10;\n" +#~ " loop {\n" +#~ " x = if x % 2 == 0 {\n" +#~ " x / 2\n" +#~ " } else {\n" +#~ " 3 * x + 1\n" +#~ " };\n" +#~ " if x == 1 {\n" +#~ " break;\n" +#~ " }\n" +#~ " }\n" +#~ " println!(\"Final x: {x}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "Break the `loop` with a value (e.g. `break 8`) and print it out." +#~ msgstr "請使用 `break 8` 等值中斷 `loop`,然後顯示出來。" + +#~ msgid "" +#~ "The [`match` keyword](https://doc.rust-lang.org/reference/expressions/" +#~ "match-expr.html) is used to match a value against one or more patterns. " +#~ "In that sense, it works like a series of `if let` expressions:" +#~ msgstr "" +#~ "[`match` 關鍵字](https://doc.rust-lang.org/reference/expressions/match-" +#~ "expr.html)是用來將值與一或多個模式進行比對。因此,這個關鍵字的運作方式類似" +#~ "於一系列的 `if let` 運算式:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " match std::env::args().next().as_deref() {\n" +#~ " Some(\"cat\") => println!(\"Will do cat things\"),\n" +#~ " Some(\"ls\") => println!(\"Will ls some files\"),\n" +#~ " Some(\"mv\") => println!(\"Let's move some files\"),\n" +#~ " Some(\"rm\") => println!(\"Uh, dangerous!\"),\n" +#~ " None => println!(\"Hmm, no program name?\"),\n" +#~ " _ => println!(\"Unknown program name!\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " match std::env::args().next().as_deref() {\n" +#~ " Some(\"cat\") => println!(\"Will do cat things\"),\n" +#~ " Some(\"ls\") => println!(\"Will ls some files\"),\n" +#~ " Some(\"mv\") => println!(\"Let's move some files\"),\n" +#~ " Some(\"rm\") => println!(\"Uh, dangerous!\"),\n" +#~ " None => println!(\"Hmm, no program name?\"),\n" +#~ " _ => println!(\"Unknown program name!\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "Save the match expression to a variable and print it out." +#~ msgstr "請將比對運算式儲存為變數,然後顯示出來。" + +#~ msgid "Remove `.as_deref()` and explain the error." +#~ msgstr "請移除 `.as_deref()` 並說明錯誤。" + +#~ msgid "" +#~ "`std::env::args().next()` returns an `Option`, but we cannot " +#~ "match against `String`." +#~ msgstr "" +#~ "`std::env::args().next()` 會傳回 `Option`,但我們無法與`String` 進" +#~ "行比對。" + +#~ msgid "" +#~ "`as_deref()` transforms an `Option` to `Option<&T::Target>`. In our " +#~ "case, this turns `Option` into `Option<&str>`." +#~ msgstr "" +#~ "`as_deref()` 會將 `Option` 轉換成 `Option<&T::Target>`。在我們的案例" +#~ "中,這會將 `Option` 轉換成`Option<&str>`。" + +#~ msgid "" +#~ "We can now use pattern matching to match against the `&str` inside " +#~ "`Option`." +#~ msgstr "我們現在可以使用模式比對,與 `Option` 內的 `&str` 進行比對。" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " let mut iter = v.into_iter();\n" +#~ " 'outer: while let Some(x) = iter.next() {\n" +#~ " println!(\"x: {x}\");\n" +#~ " let mut i = 0;\n" +#~ " while i < x {\n" +#~ " println!(\"x: {x}, i: {i}\");\n" +#~ " i += 1;\n" +#~ " if i == 3 {\n" +#~ " break 'outer;\n" +#~ " }\n" +#~ " }\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " let mut iter = v.into_iter();\n" +#~ " 'outer: while let Some(x) = iter.next() {\n" +#~ " println!(\"x: {x}\");\n" +#~ " let mut i = 0;\n" +#~ " while i < x {\n" +#~ " println!(\"x: {x}, i: {i}\");\n" +#~ " i += 1;\n" +#~ " if i == 3 {\n" +#~ " break 'outer;\n" +#~ " }\n" +#~ " }\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "In this case we break the outer loop after 3 iterations of the inner loop." +#~ msgstr "" +#~ "在這個範例中,內層迴圈經過三次迭代後,我們使用 `break` 跳出外層迴圈。" + +#~ msgid "The common vocabulary types include:" +#~ msgstr "常見的詞彙型別包括:" + +#~ msgid "" +#~ "[`Option` and `Result`](std/option-result.md) types: used for optional " +#~ "values and [error handling](error-handling.md)." +#~ msgstr "" +#~ "[`Option` 和 `Result`](std/option-result.md) 型別:用於選擇性的值和[錯誤處" +#~ "理](error-handling.md)。" + +#~ msgid "" +#~ "[`String`](std/string.md): the default string type used for owned data." +#~ msgstr "[`String`](std/string.md):用於自有資料的預設字串型別。" + +#~ msgid "[`Vec`](std/vec.md): a standard extensible vector." +#~ msgstr "[`Vec`](std/vec.md):標準的可延伸向量。" + +#~ msgid "" +#~ "[`HashMap`](std/hashmap.md): a hash map type with a configurable hashing " +#~ "algorithm." +#~ msgstr "[`HashMap`](std/hashmap.md):採用可設定雜湊演算法的雜湊映射型別。" + +#~ msgid "[`Box`](std/box.md): an owned pointer for heap-allocated data." +#~ msgstr "[`Box`](std/box.md):堆積配置資料的擁有所有權的指標。" + +#~ msgid "" +#~ "[`Rc`](std/rc.md): a shared reference-counted pointer for heap-allocated " +#~ "data." +#~ msgstr "[`Rc`](std/rc.md):堆積配置資料的共用參考指標。" + +#~ msgid "`Option` and `Result`" +#~ msgstr "`Option` 和 `Result`" + +#~ msgid "The types represent optional data:" +#~ msgstr "這些型別代表選擇性的資料:" + +#~ msgid "`Option<&T>` has zero space overhead compared to `&T`." +#~ msgstr "相較於 `&T`,`Option<&T>` 的空間開銷為零。" + +#~ msgid "`binary_search` returns `Result`." +#~ msgstr "`binary_search` 會回傳 `Result`。" + +#~ msgid "If found, `Result::Ok` holds the index where the element is found." +#~ msgstr "如果找到該元素,`Result::Ok` 會保留該元素所在位置的索引。" + +#~ msgid "" +#~ "Otherwise, `Result::Err` contains the index where such an element should " +#~ "be inserted." +#~ msgstr "如果沒有找到,`Result::Err` 會包含應插入這類元素的索引。" + +#~ msgid "" +#~ "Show iterating over a vector and mutating the value: `for e in &mut v " +#~ "{ *e += 50; }`" +#~ msgstr "示範如何對向量進行疊代並修改值:`for e in &mut v { *e += 50; }`" + +#~ msgid "" +#~ "In the above example, you can even leave out the `*` in the `println!` " +#~ "statement thanks to `Deref`. " +#~ msgstr "上面的範例使用 `Deref`,因此 `println!` 陳述式甚至可以省略 `*`。" + +#~ msgid "Box with Recursive Data Structures" +#~ msgstr "包含遞迴資料結構的 Box" + +#, fuzzy +#~ msgid "" +#~ "If you need to mutate the data inside an `Rc`, you will need to wrap the " +#~ "data in a type such as [`Cell` or `RefCell`](../concurrency/shared_state/" +#~ "arc.md)." +#~ msgstr "" +#~ "如要在 `Rc` 內修改資料,必須將資料加入 [`Cell` 或 `RefCell`](../" +#~ "concurrency/shared_state/arc.md) 等型別中。\\* 如果是多執行緒的環境,請參" +#~ "閱 [`Arc`](https://doc.rust-lang.org/std/sync/struct.Mutex.html)。\\* 您可" +#~ "以將共用指標「降級」為 [`Weak`](https://doc.rust-lang.org/std/rc/struct." +#~ "Weak.html) 指標,建立之後會捨棄的循環。" + +#~ msgid "Like C++'s `std::shared_ptr`." +#~ msgstr "Rust 的 `Rc` 就好比是 C++ 的 `std::shared_ptr`。" + +#~ msgid "" +#~ "Compare the different datatypes mentioned. `Box` enables (im)mutable " +#~ "borrows that are enforced at compile time. `RefCell` enables (im)mutable " +#~ "borrows that are enforced at run time and will panic if it fails at " +#~ "runtime." +#~ msgstr "" +#~ "比較提及的不同資料型別。`Box` 可啟用在編譯時強制執行的可變/不可變借用。" +#~ "`RefCell` 可啟用在執行階段強制執行的可變/不可變借用,如果在執行階段失敗," +#~ "將觸發恐慌。" + +#~ msgid "Day 2: Afternoon Exercises" +#~ msgstr "第 2 天:下午練習" + +#~ msgid "" +#~ "The exercises for this afternoon will focus on strings and iterators." +#~ msgstr "今天下午的練習著重在字串和疊代器。" + +#~ msgid "" +#~ "In this exercise, you are implementing a routing component of a web " +#~ "server. The server is configured with a number of _path prefixes_ which " +#~ "are matched against _request paths_. The path prefixes can contain a " +#~ "wildcard character which matches a full segment. See the unit tests below." +#~ msgstr "" +#~ "在本次練習中,您將實作網路伺服器的路由元件。伺服器設定了多個與「要求路徑」" +#~ "__相符的「路徑前置字元」__。路徑前置字元可包含與完整片段相符的萬用字元。請" +#~ "參閱下方的單元測試。" + +#~ msgid "" +#~ "Traits: deriving traits, default methods, and important standard library " +#~ "traits." +#~ msgstr "特徵:衍生特徵、預設方法,以及重要的標準程式庫特徵。" + +#~ msgid "" +#~ "Generics: generic data types, generic methods, monomorphization, and " +#~ "trait objects." +#~ msgstr "泛型:泛型資料型別、泛型方法、單型,以及特徵物件。" + +#~ msgid "Testing: unit tests, documentation tests, and integration tests." +#~ msgstr "測試:單元測試、說明文件測試,以及整合測試。" + +#~ msgid "" +#~ "Unsafe Rust: raw pointers, static variables, unsafe functions, and extern " +#~ "functions." +#~ msgstr "不安全的 Rust:原始指標、靜態變數、不安全的函式,以及 extern 函式。" + +#~ msgid "Try declaring a new variable `let p = Point { x: 5, y: 10.0 };`." +#~ msgstr "試著宣告一個新的變數 `let p = Point { x: 5, y: 10.0 };`." + +#~ msgid "Fix the code to allow points that have elements of different types." +#~ msgstr "修改程式碼,讓 points 能擁有不同型別的元素。" + +#~ msgid "You can declare a generic type on your `impl` block:" +#~ msgstr "你可以將 `impl` 區塊宣告為泛型型別:" + +#~ msgid "" +#~ "Generic code is turned into non-generic code based on the call sites:" +#~ msgstr "" +#~ "Rust 在編譯時進行單型化 (Monomorphization),根據不同呼叫者,將泛型程式碼轉" +#~ "換成實際型別的程式碼:" + +#~ msgid "behaves as if you wrote" +#~ msgstr "以上程式碼等同於下方的程式碼" + +#~ msgid "You can let the compiler derive a number of traits:" +#~ msgstr "您可以讓編譯器衍生多種特徵:" + +#~ msgid "Traits can implement behavior in terms of other trait methods:" +#~ msgstr "特徵可以依照其他特徵方法來實作行為:" + +#~ msgid "" +#~ "Traits may specify pre-implemented (default) methods and methods that " +#~ "users are required to implement themselves. Methods with default " +#~ "implementations can rely on required methods." +#~ msgstr "" +#~ "特徵可能會指定預先實作的 (預設) 方法,以及使用者必須自行實作的方法。採用預" +#~ "設實作項目的方法可以信賴必要方法。" + +#~ msgid "" +#~ "```rust,ignore\n" +#~ "fn duplicate(a: T) -> (T, T)\n" +#~ "where\n" +#~ " T: Clone,\n" +#~ "{\n" +#~ " (a.clone(), a.clone())\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,ignore\n" +#~ "fn duplicate(a: T) -> (T, T)\n" +#~ "where\n" +#~ " T: Clone,\n" +#~ "{\n" +#~ " (a.clone(), a.clone())\n" +#~ "}\n" +#~ "```" + +#~ msgid "`impl Trait` allows you to work with types which you cannot name." +#~ msgstr "`impl Trait` 可讓您使用無法命名的型別。" + +#~ msgid "" +#~ "This example is great, because it uses `impl Display` twice. It helps to " +#~ "explain that nothing here enforces that it is _the same_ `impl Display` " +#~ "type. If we used a single `T: Display`, it would enforce the constraint " +#~ "that input `T` and return `T` type are the same type. It would not work " +#~ "for this particular function, as the type we expect as input is likely " +#~ "not what `format!` returns. If we wanted to do the same via `: Display` " +#~ "syntax, we'd need two independent generic parameters." +#~ msgstr "" +#~ "這個例子非常好,因為 `impl Display` 使用了兩次。這有助於說明此處沒有 任何" +#~ "項目會強制使用「相同的」`impl Display` 型別。如果我們使用單一的 `T: " +#~ "Display`,則會強制限制「輸入」`T` 和「回傳」`T` 屬於同一型別。 但這並不適" +#~ "合這個特定函式,因為我們預期做為「輸入」的型別不一定 會是 `format!` 回傳的" +#~ "內容。如要透過 `: Display` 語法執行相同操作,我們會 需要兩個獨立的泛型參" +#~ "數。" + +#~ msgid "" +#~ "We will now look at some of the most common traits of the Rust standard " +#~ "library:" +#~ msgstr "現在來探討 Rust 標準程式庫最常見的幾個特徵:" + +#~ msgid "" +#~ "[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) and " +#~ "[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator." +#~ "html) used in `for` loops," +#~ msgstr "" +#~ "[`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html) 和 " +#~ "[`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator." +#~ "html) 用於 `for` 迴圈。" + +#~ msgid "" +#~ "[`From`](https://doc.rust-lang.org/std/convert/trait.From.html) and " +#~ "[`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) used to " +#~ "convert values," +#~ msgstr "" +#~ "[`From`](https://doc.rust-lang.org/std/convert/trait.From.html) 和 " +#~ "[`Into`](https://doc.rust-lang.org/std/convert/trait.Into.html) 用來轉換" +#~ "值。" + +#~ msgid "" +#~ "[`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) and [`Write`]" +#~ "(https://doc.rust-lang.org/std/io/trait.Write.html) used for IO," +#~ msgstr "" +#~ "[`Read`](https://doc.rust-lang.org/std/io/trait.Read.html) 和 [`Write`]" +#~ "(https://doc.rust-lang.org/std/io/trait.Write.html) 用於 IO。" + +#~ msgid "" +#~ "[`Add`](https://doc.rust-lang.org/std/ops/trait.Add.html), [`Mul`]" +#~ "(https://doc.rust-lang.org/std/ops/trait.Mul.html), ... used for operator " +#~ "overloading, and" +#~ msgstr "" +#~ "[`Add`](https://doc.rust-lang.org/std/ops/trait.Add.html)、[`Mul`]" +#~ "(https://doc.rust-lang.org/std/ops/trait.Mul.html) 等用於運算子超載。" + +#~ msgid "" +#~ "[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) " +#~ "used to construct a default instance of a type." +#~ msgstr "" +#~ "[`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) 用於" +#~ "建構型別的預設執行個體。" + +#~ msgid "" +#~ "`Iterator` implements `fn collect(self) -> B where B: " +#~ "FromIterator, Self: Sized`" +#~ msgstr "" +#~ "`Iterator` implements `fn collect(self) -> B where B: " +#~ "FromIterator, Self: Sized`" + +#~ msgid "`Add`, `Mul`, ..." +#~ msgstr "`Add`、`Mul`..." + +#~ msgid "Day 3: Morning Exercises" +#~ msgstr "第 3 天:上午練習" + +#~ msgid "" +#~ "Let us design a classical GUI library using our new knowledge of traits " +#~ "and trait objects." +#~ msgstr "我們對特徵和特徵物件有了新的瞭解,現在來設計經典的 GUI 程式庫吧!" + +#~ msgid "We will have a number of widgets in our library:" +#~ msgstr "我們的程式庫中會有許多小工具:" + +#~ msgid "`Window`: has a `title` and contains other widgets." +#~ msgstr "`Window`:有 `title` 且包含其他小工具。" + +#~ msgid "" +#~ "`Button`: has a `label` and a callback function which is invoked when the " +#~ "button is pressed." +#~ msgstr "`Button`:含有 `label` 和回呼函式,按下按鈕就會叫用這個函式。" + +#~ msgid "`Label`: has a `label`." +#~ msgstr "`Label`:含有 `label`。" + +#~ msgid "The widgets will implement a `Widget` trait, see below." +#~ msgstr "小工具會實作 `Widget` 特徵,請參閱下文。" + +#~ msgid "" +#~ "Copy the code below to , fill in the missing " +#~ "`draw_into` methods so that you implement the `Widget` trait:" +#~ msgstr "" +#~ "請將以下程式碼複製到 ,並填入缺少的 " +#~ "`draw_into` 方法,以便實作 `Widget` 特徵:" + +#~ msgid "The output of the above program can be something simple like this:" +#~ msgstr "上方程式的輸出內容可以很簡單,像下面這樣:" + +#~ msgid "" +#~ "If you want to draw aligned text, you can use the [fill/alignment]" +#~ "(https://doc.rust-lang.org/std/fmt/index.html#fillalignment) formatting " +#~ "operators. In particular, notice how you can pad with different " +#~ "characters (here a `'/'`) and how you can control alignment:" +#~ msgstr "" +#~ "如要繪製對齊的文字,可以使用 [fill/alignment](https://doc.rust-lang.org/" +#~ "std/fmt/index.html#fillalignment) 格式化運算子。請特別注意如何使用不同的字" +#~ "元 (此處為 `'/'`) 設定邊框間距,以及可以如何控制對齊方式:" + +#~ msgid "" +#~ "Using such alignment tricks, you can for example produce output like this:" +#~ msgstr "使用這種對齊技巧,您可以產生如下的輸出內容:" + +#~ msgid "Error handling in Rust is done using explicit control flow:" +#~ msgstr "在 Rust 中,是透過明確的控制流程完成錯誤處理作業:" + +#~ msgid "Functions that can have errors list this in their return type," +#~ msgstr "可能含有錯誤的函式會在回傳型別中列出相關資訊。" + +#~ msgid "There are no exceptions." +#~ msgstr "沒有任何例外。" + +#~ msgid "" +#~ "```rust,editable,should_panic\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " println!(\"v[100]: {}\", v[100]);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,should_panic\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " println!(\"v[100]: {}\", v[100]);\n" +#~ "}\n" +#~ "```" + +#~ msgid "Catching the Stack Unwinding" +#~ msgstr "擷取解開堆疊的動作" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::panic;\n" +#~ "\n" +#~ "let result = panic::catch_unwind(|| {\n" +#~ " println!(\"hello!\");\n" +#~ "});\n" +#~ "assert!(result.is_ok());\n" +#~ "\n" +#~ "let result = panic::catch_unwind(|| {\n" +#~ " panic!(\"oh no!\");\n" +#~ "});\n" +#~ "assert!(result.is_err());\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::panic;\n" +#~ "\n" +#~ "let result = panic::catch_unwind(|| {\n" +#~ " println!(\"hello!\");\n" +#~ "});\n" +#~ "assert!(result.is_ok());\n" +#~ "\n" +#~ "let result = panic::catch_unwind(|| {\n" +#~ " panic!(\"oh no!\");\n" +#~ "});\n" +#~ "assert!(result.is_err());\n" +#~ "```" + +#~ msgid "" +#~ "We have already seen the `Result` enum. This is used pervasively when " +#~ "errors are expected as part of normal operation:" +#~ msgstr "" +#~ "我們先前介紹了 `Result` 列舉。當正常運作過程中預期發生錯誤時,普遍都會使用" +#~ "這個列舉:" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::fs::File;\n" +#~ "use std::io::Read;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let file = File::open(\"diary.txt\");\n" +#~ " match file {\n" +#~ " Ok(mut file) => {\n" +#~ " let mut contents = String::new();\n" +#~ " file.read_to_string(&mut contents);\n" +#~ " println!(\"Dear diary: {contents}\");\n" +#~ " },\n" +#~ " Err(err) => {\n" +#~ " println!(\"The diary could not be opened: {err}\");\n" +#~ " }\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::fs::File;\n" +#~ "use std::io::Read;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let file = File::open(\"diary.txt\");\n" +#~ " match file {\n" +#~ " Ok(mut file) => {\n" +#~ " let mut contents = String::new();\n" +#~ " file.read_to_string(&mut contents);\n" +#~ " println!(\"Dear diary: {contents}\");\n" +#~ " },\n" +#~ " Err(err) => {\n" +#~ " println!(\"The diary could not be opened: {err}\");\n" +#~ " }\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "Propagating Errors with `?`" +#~ msgstr "使用 `?` 傳播錯誤" + +#~ msgid "" +#~ "The try-operator `?` is used to return errors to the caller. It lets you " +#~ "turn the common" +#~ msgstr "try 運算子 `?` 用於將錯誤傳回呼叫端,讓您將下列常見的程式碼:" + +#~ msgid "" +#~ "```rust,ignore\n" +#~ "match some_expression {\n" +#~ " Ok(value) => value,\n" +#~ " Err(err) => return Err(err),\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,ignore\n" +#~ "match some_expression {\n" +#~ " Ok(value) => value,\n" +#~ " Err(err) => return Err(err),\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,ignore\n" +#~ "some_expression?\n" +#~ "```" +#~ msgstr "" +#~ "```rust,ignore\n" +#~ "some_expression?\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::fs;\n" +#~ "use std::io::{self, Read};\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let username_file_result = fs::File::open(path);\n" +#~ " let mut username_file = match username_file_result {\n" +#~ " Ok(file) => file,\n" +#~ " Err(err) => return Err(err),\n" +#~ " };\n" +#~ "\n" +#~ " let mut username = String::new();\n" +#~ " match username_file.read_to_string(&mut username) {\n" +#~ " Ok(_) => Ok(username),\n" +#~ " Err(err) => Err(err),\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"alice\").unwrap();\n" +#~ " let username = read_username(\"config.dat\");\n" +#~ " println!(\"username or error: {username:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::fs;\n" +#~ "use std::io::{self, Read};\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let username_file_result = fs::File::open(path);\n" +#~ " let mut username_file = match username_file_result {\n" +#~ " Ok(file) => file,\n" +#~ " Err(err) => return Err(err),\n" +#~ " };\n" +#~ "\n" +#~ " let mut username = String::new();\n" +#~ " match username_file.read_to_string(&mut username) {\n" +#~ " Ok(_) => Ok(username),\n" +#~ " Err(err) => Err(err),\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"alice\").unwrap();\n" +#~ " let username = read_username(\"config.dat\");\n" +#~ " println!(\"username or error: {username:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,ignore\n" +#~ "expression?\n" +#~ "```" +#~ msgstr "" +#~ "```rust,ignore\n" +#~ "expression?\n" +#~ "```" + +#~ msgid "" +#~ "```rust,ignore\n" +#~ "match expression {\n" +#~ " Ok(value) => value,\n" +#~ " Err(err) => return Err(From::from(err)),\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,ignore\n" +#~ "match expression {\n" +#~ " Ok(value) => value,\n" +#~ " Err(err) => return Err(From::from(err)),\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::error::Error;\n" +#~ "use std::fmt::{self, Display, Formatter};\n" +#~ "use std::fs::{self, File};\n" +#~ "use std::io::{self, Read};\n" +#~ "\n" +#~ "#[derive(Debug)]\n" +#~ "enum ReadUsernameError {\n" +#~ " IoError(io::Error),\n" +#~ " EmptyUsername(String),\n" +#~ "}\n" +#~ "\n" +#~ "impl Error for ReadUsernameError {}\n" +#~ "\n" +#~ "impl Display for ReadUsernameError {\n" +#~ " fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n" +#~ " match self {\n" +#~ " Self::IoError(e) => write!(f, \"IO error: {e}\"),\n" +#~ " Self::EmptyUsername(filename) => write!(f, \"Found no " +#~ "username in {filename}\"),\n" +#~ " }\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "impl From for ReadUsernameError {\n" +#~ " fn from(err: io::Error) -> ReadUsernameError {\n" +#~ " ReadUsernameError::IoError(err)\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " File::open(path)?.read_to_string(&mut username)?;\n" +#~ " if username.is_empty() {\n" +#~ " return Err(ReadUsernameError::EmptyUsername(String::" +#~ "from(path)));\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " let username = read_username(\"config.dat\");\n" +#~ " println!(\"username or error: {username:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::error::Error;\n" +#~ "use std::fmt::{self, Display, Formatter};\n" +#~ "use std::fs::{self, File};\n" +#~ "use std::io::{self, Read};\n" +#~ "\n" +#~ "#[derive(Debug)]\n" +#~ "enum ReadUsernameError {\n" +#~ " IoError(io::Error),\n" +#~ " EmptyUsername(String),\n" +#~ "}\n" +#~ "\n" +#~ "impl Error for ReadUsernameError {}\n" +#~ "\n" +#~ "impl Display for ReadUsernameError {\n" +#~ " fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n" +#~ " match self {\n" +#~ " Self::IoError(e) => write!(f, \"IO error: {e}\"),\n" +#~ " Self::EmptyUsername(filename) => write!(f, \"Found no " +#~ "username in {filename}\"),\n" +#~ " }\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "impl From for ReadUsernameError {\n" +#~ " fn from(err: io::Error) -> ReadUsernameError {\n" +#~ " ReadUsernameError::IoError(err)\n" +#~ " }\n" +#~ "}\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " File::open(path)?.read_to_string(&mut username)?;\n" +#~ " if username.is_empty() {\n" +#~ " return Err(ReadUsernameError::EmptyUsername(String::" +#~ "from(path)));\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " let username = read_username(\"config.dat\");\n" +#~ " println!(\"username or error: {username:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::{fs, io};\n" +#~ "use std::io::Read;\n" +#~ "use thiserror::Error;\n" +#~ "\n" +#~ "#[derive(Debug, Error)]\n" +#~ "enum ReadUsernameError {\n" +#~ " #[error(\"Could not read: {0}\")]\n" +#~ " IoError(#[from] io::Error),\n" +#~ " #[error(\"Found no username in {0}\")]\n" +#~ " EmptyUsername(String),\n" +#~ "}\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " fs::File::open(path)?.read_to_string(&mut username)?;\n" +#~ " if username.is_empty() {\n" +#~ " return Err(ReadUsernameError::EmptyUsername(String::" +#~ "from(path)));\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " match read_username(\"config.dat\") {\n" +#~ " Ok(username) => println!(\"Username: {username}\"),\n" +#~ " Err(err) => println!(\"Error: {err}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::{fs, io};\n" +#~ "use std::io::Read;\n" +#~ "use thiserror::Error;\n" +#~ "\n" +#~ "#[derive(Debug, Error)]\n" +#~ "enum ReadUsernameError {\n" +#~ " #[error(\"Could not read: {0}\")]\n" +#~ " IoError(#[from] io::Error),\n" +#~ " #[error(\"Found no username in {0}\")]\n" +#~ " EmptyUsername(String),\n" +#~ "}\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " fs::File::open(path)?.read_to_string(&mut username)?;\n" +#~ " if username.is_empty() {\n" +#~ " return Err(ReadUsernameError::EmptyUsername(String::" +#~ "from(path)));\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " match read_username(\"config.dat\") {\n" +#~ " Ok(username) => println!(\"Username: {username}\"),\n" +#~ " Err(err) => println!(\"Error: {err}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "`thiserror`'s derive macro automatically implements `std::error::Error`, " +#~ "and optionally `Display` (if the `#[error(...)]` attributes are provided) " +#~ "and `From` (if the `#[from]` attribute is added). It also works for " +#~ "structs." +#~ msgstr "" +#~ "`thiserror` 的衍生巨集會自動實作 `std::error::Error`,並視情況實作 " +#~ "`Display` (如果提供了 `#[error(...)]` 屬性的話) 和 `From` (如果新增了 " +#~ "`#[from]` 屬性的話)。上述原則也適用於結構體。" + +#~ msgid "" +#~ "It doesn't affect your public API, which makes it good for libraries." +#~ msgstr "這個不會影響你的公用API,因此這對程式庫很好。" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::fs::{self, File};\n" +#~ "use std::io::Read;\n" +#~ "use thiserror::Error;\n" +#~ "use std::error::Error;\n" +#~ "\n" +#~ "#[derive(Clone, Debug, Eq, Error, PartialEq)]\n" +#~ "#[error(\"Found no username in {0}\")]\n" +#~ "struct EmptyUsernameError(String);\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result> {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " File::open(path)?.read_to_string(&mut username)?;\n" +#~ " if username.is_empty() {\n" +#~ " return Err(EmptyUsernameError(String::from(path)).into());\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " match read_username(\"config.dat\") {\n" +#~ " Ok(username) => println!(\"Username: {username}\"),\n" +#~ " Err(err) => println!(\"Error: {err}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::fs::{self, File};\n" +#~ "use std::io::Read;\n" +#~ "use thiserror::Error;\n" +#~ "use std::error::Error;\n" +#~ "\n" +#~ "#[derive(Clone, Debug, Eq, Error, PartialEq)]\n" +#~ "#[error(\"Found no username in {0}\")]\n" +#~ "struct EmptyUsernameError(String);\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result> {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " File::open(path)?.read_to_string(&mut username)?;\n" +#~ " if username.is_empty() {\n" +#~ " return Err(EmptyUsernameError(String::from(path)).into());\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " match read_username(\"config.dat\") {\n" +#~ " Ok(username) => println!(\"Username: {username}\"),\n" +#~ " Err(err) => println!(\"Error: {err}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "The widely used [anyhow](https://docs.rs/anyhow/) crate can help you add " +#~ "contextual information to your errors and allows you to have fewer custom " +#~ "error types:" +#~ msgstr "" +#~ "透過廣泛使用的 [anyhow](https://docs.rs/anyhow/) crate,您可以為錯誤添加背" +#~ "景資訊,並減少自訂錯誤型別的數量:" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::{fs, io};\n" +#~ "use std::io::Read;\n" +#~ "use anyhow::{Context, Result, bail};\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " fs::File::open(path)\n" +#~ " .with_context(|| format!(\"Failed to open {path}\"))?\n" +#~ " .read_to_string(&mut username)\n" +#~ " .context(\"Failed to read\")?;\n" +#~ " if username.is_empty() {\n" +#~ " bail!(\"Found no username in {path}\");\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " match read_username(\"config.dat\") {\n" +#~ " Ok(username) => println!(\"Username: {username}\"),\n" +#~ " Err(err) => println!(\"Error: {err:?}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::{fs, io};\n" +#~ "use std::io::Read;\n" +#~ "use anyhow::{Context, Result, bail};\n" +#~ "\n" +#~ "fn read_username(path: &str) -> Result {\n" +#~ " let mut username = String::with_capacity(100);\n" +#~ " fs::File::open(path)\n" +#~ " .with_context(|| format!(\"Failed to open {path}\"))?\n" +#~ " .read_to_string(&mut username)\n" +#~ " .context(\"Failed to read\")?;\n" +#~ " if username.is_empty() {\n" +#~ " bail!(\"Found no username in {path}\");\n" +#~ " }\n" +#~ " Ok(username)\n" +#~ "}\n" +#~ "\n" +#~ "fn main() {\n" +#~ " //fs::write(\"config.dat\", \"\").unwrap();\n" +#~ " match read_username(\"config.dat\") {\n" +#~ " Ok(username) => println!(\"Username: {username}\"),\n" +#~ " Err(err) => println!(\"Error: {err:?}\"),\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "Mark unit tests with `#[test]`:" +#~ msgstr "用 `#[test]` 標記單元測試:" + +#~ msgid "Use `cargo test` to find and run the unit tests." +#~ msgstr "用 `cargo test` 尋找並執行單元測試。" + +#~ msgid "" +#~ "Unit tests are often put in a nested module (run tests on the [Playground]" +#~ "(https://play.rust-lang.org/)):" +#~ msgstr "" +#~ "單元測試通常會位於巢狀模組中 (在 [Playground](https://play.rust-lang." +#~ "org/) 上執行測試):" + +#~ msgid "Useful crates for writing tests" +#~ msgstr "有助於編寫測試的 crate" + +#~ msgid "Rust comes with only basic support for writing tests." +#~ msgstr "Rust 只提供基本的編寫測試支援。" + +#~ msgid "" +#~ "Here are some additional crates which we recommend for writing tests:" +#~ msgstr "以下列出幾個額外的 crate,建議您在編寫測試時使用:" + +#~ msgid "" +#~ "[proptest](https://docs.rs/proptest): Property-based testing for Rust." +#~ msgstr "" +#~ "[proptest](https://docs.rs/proptest):讓您對 Rust 執行以屬性為基礎的測試。" + +#~ msgid "" +#~ "[rstest](https://docs.rs/rstest): Support for fixtures and parameterised " +#~ "tests." +#~ msgstr "[rstest](https://docs.rs/rstest):支援 Fixture 和參數化測試。" + +#~ msgid "Calling External Code" +#~ msgstr "呼叫外部程式碼" + +#~ msgid "" +#~ "Functions from other languages might violate the guarantees of Rust. " +#~ "Calling them is thus unsafe:" +#~ msgstr "其他語言的函式可能會違反 Rust 保證,因此呼叫這類函式並不安全:" + +#~ msgid "Day 3: Afternoon Exercises" +#~ msgstr "第 3 天:下午練習" + +#~ msgid "Let us build a safe wrapper for reading directory content!" +#~ msgstr "我們來建構用於讀取目錄內容的安全包裝函式吧!" + +#~ msgid "" +#~ "After looking at the exercise, you can look at the [solution](solutions-" +#~ "afternoon.md) provided." +#~ msgstr "" +#~ "完成練習後,您可以看看我們提供的[解決方案](solutions-afternoon.md)。" + +#~ msgid "" +#~ "```java\n" +#~ "package com.example.birthdayservice;\n" +#~ "\n" +#~ "/** Birthday service interface. */\n" +#~ "interface IBirthdayService {\n" +#~ " /** Generate a Happy Birthday message. */\n" +#~ " String wishHappyBirthday(String name, int years, in String[] text);\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```java\n" +#~ "package com.example.birthdayservice;\n" +#~ "\n" +#~ "/** 生日功能介面 */\n" +#~ "interface IBirthdayService {\n" +#~ " /** 生成一段生日快樂的祝賀訊息 */\n" +#~ " String wishHappyBirthday(String name, int years, in String[] text);\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::thread;\n" +#~ "use std::time::Duration;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " thread::spawn(|| {\n" +#~ " for i in 1..10 {\n" +#~ " println!(\"Count in thread: {i}!\");\n" +#~ " thread::sleep(Duration::from_millis(5));\n" +#~ " }\n" +#~ " });\n" +#~ "\n" +#~ " for i in 1..5 {\n" +#~ " println!(\"Main thread: {i}\");\n" +#~ " thread::sleep(Duration::from_millis(5));\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::thread;\n" +#~ "use std::time::Duration;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " thread::spawn(|| {\n" +#~ " for i in 1..10 {\n" +#~ " println!(\"Count in thread: {i}!\");\n" +#~ " thread::sleep(Duration::from_millis(5));\n" +#~ " }\n" +#~ " });\n" +#~ "\n" +#~ " for i in 1..5 {\n" +#~ " println!(\"Main thread: {i}\");\n" +#~ " thread::sleep(Duration::from_millis(5));\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "Notice that the thread is stopped before it reaches 10 — the main thread " +#~ "is not waiting." +#~ msgstr "" +#~ "請注意,執行緒會在達到 10 之前停止運作,因為主執行緒不會 等待其完成運作。" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let s = String::from(\"Hello\");\n" +#~ "\n" +#~ " thread::spawn(|| {\n" +#~ " println!(\"Length: {}\", s.len());\n" +#~ " });\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let s = String::from(\"Hello\");\n" +#~ "\n" +#~ " thread::spawn(|| {\n" +#~ " println!(\"Length: {}\", s.len());\n" +#~ " });\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let s = String::from(\"Hello\");\n" +#~ "\n" +#~ " thread::scope(|scope| {\n" +#~ " scope.spawn(|| {\n" +#~ " println!(\"Length: {}\", s.len());\n" +#~ " });\n" +#~ " });\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let s = String::from(\"Hello\");\n" +#~ "\n" +#~ " thread::scope(|scope| {\n" +#~ " scope.spawn(|| {\n" +#~ " println!(\"Length: {}\", s.len());\n" +#~ " });\n" +#~ " });\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::sync::mpsc;\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let (tx, rx) = mpsc::channel();\n" +#~ "\n" +#~ " tx.send(10).unwrap();\n" +#~ " tx.send(20).unwrap();\n" +#~ "\n" +#~ " println!(\"Received: {:?}\", rx.recv());\n" +#~ " println!(\"Received: {:?}\", rx.recv());\n" +#~ "\n" +#~ " let tx2 = tx.clone();\n" +#~ " tx2.send(30).unwrap();\n" +#~ " println!(\"Received: {:?}\", rx.recv());\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::sync::mpsc;\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let (tx, rx) = mpsc::channel();\n" +#~ "\n" +#~ " tx.send(10).unwrap();\n" +#~ " tx.send(20).unwrap();\n" +#~ "\n" +#~ " println!(\"Received: {:?}\", rx.recv());\n" +#~ " println!(\"Received: {:?}\", rx.recv());\n" +#~ "\n" +#~ " let tx2 = tx.clone();\n" +#~ " tx2.send(30).unwrap();\n" +#~ " println!(\"Received: {:?}\", rx.recv());\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::sync::mpsc;\n" +#~ "use std::thread;\n" +#~ "use std::time::Duration;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let (tx, rx) = mpsc::channel();\n" +#~ "\n" +#~ " thread::spawn(move || {\n" +#~ " let thread_id = thread::current().id();\n" +#~ " for i in 1..10 {\n" +#~ " tx.send(format!(\"Message {i}\")).unwrap();\n" +#~ " println!(\"{thread_id:?}: sent Message {i}\");\n" +#~ " }\n" +#~ " println!(\"{thread_id:?}: done\");\n" +#~ " });\n" +#~ " thread::sleep(Duration::from_millis(100));\n" +#~ "\n" +#~ " for msg in rx.iter() {\n" +#~ " println!(\"Main: got {msg}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::sync::mpsc;\n" +#~ "use std::thread;\n" +#~ "use std::time::Duration;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let (tx, rx) = mpsc::channel();\n" +#~ "\n" +#~ " thread::spawn(move || {\n" +#~ " let thread_id = thread::current().id();\n" +#~ " for i in 1..10 {\n" +#~ " tx.send(format!(\"Message {i}\")).unwrap();\n" +#~ " println!(\"{thread_id:?}: sent Message {i}\");\n" +#~ " }\n" +#~ " println!(\"{thread_id:?}: done\");\n" +#~ " });\n" +#~ " thread::sleep(Duration::from_millis(100));\n" +#~ "\n" +#~ " for msg in rx.iter() {\n" +#~ " println!(\"Main: got {msg}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::sync::mpsc;\n" +#~ "use std::thread;\n" +#~ "use std::time::Duration;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let (tx, rx) = mpsc::sync_channel(3);\n" +#~ "\n" +#~ " thread::spawn(move || {\n" +#~ " let thread_id = thread::current().id();\n" +#~ " for i in 1..10 {\n" +#~ " tx.send(format!(\"Message {i}\")).unwrap();\n" +#~ " println!(\"{thread_id:?}: sent Message {i}\");\n" +#~ " }\n" +#~ " println!(\"{thread_id:?}: done\");\n" +#~ " });\n" +#~ " thread::sleep(Duration::from_millis(100));\n" +#~ "\n" +#~ " for msg in rx.iter() {\n" +#~ " println!(\"Main: got {msg}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::sync::mpsc;\n" +#~ "use std::thread;\n" +#~ "use std::time::Duration;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let (tx, rx) = mpsc::sync_channel(3);\n" +#~ "\n" +#~ " thread::spawn(move || {\n" +#~ " let thread_id = thread::current().id();\n" +#~ " for i in 1..10 {\n" +#~ " tx.send(format!(\"Message {i}\")).unwrap();\n" +#~ " println!(\"{thread_id:?}: sent Message {i}\");\n" +#~ " }\n" +#~ " println!(\"{thread_id:?}: done\");\n" +#~ " });\n" +#~ " thread::sleep(Duration::from_millis(100));\n" +#~ "\n" +#~ " for msg in rx.iter() {\n" +#~ " println!(\"Main: got {msg}\");\n" +#~ " }\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::thread;\n" +#~ "use std::sync::Arc;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = Arc::new(vec![10, 20, 30]);\n" +#~ " let mut handles = Vec::new();\n" +#~ " for _ in 1..5 {\n" +#~ " let v = Arc::clone(&v);\n" +#~ " handles.push(thread::spawn(move || {\n" +#~ " let thread_id = thread::current().id();\n" +#~ " println!(\"{thread_id:?}: {v:?}\");\n" +#~ " }));\n" +#~ " }\n" +#~ "\n" +#~ " handles.into_iter().for_each(|h| h.join().unwrap());\n" +#~ " println!(\"v: {v:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::thread;\n" +#~ "use std::sync::Arc;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = Arc::new(vec![10, 20, 30]);\n" +#~ " let mut handles = Vec::new();\n" +#~ " for _ in 1..5 {\n" +#~ " let v = Arc::clone(&v);\n" +#~ " handles.push(thread::spawn(move || {\n" +#~ " let thread_id = thread::current().id();\n" +#~ " println!(\"{thread_id:?}: {v:?}\");\n" +#~ " }));\n" +#~ " }\n" +#~ "\n" +#~ " handles.into_iter().for_each(|h| h.join().unwrap());\n" +#~ " println!(\"v: {v:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::sync::Mutex;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = Mutex::new(vec![10, 20, 30]);\n" +#~ " println!(\"v: {:?}\", v.lock().unwrap());\n" +#~ "\n" +#~ " {\n" +#~ " let mut guard = v.lock().unwrap();\n" +#~ " guard.push(40);\n" +#~ " }\n" +#~ "\n" +#~ " println!(\"v: {:?}\", v.lock().unwrap());\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::sync::Mutex;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = Mutex::new(vec![10, 20, 30]);\n" +#~ " println!(\"v: {:?}\", v.lock().unwrap());\n" +#~ "\n" +#~ " {\n" +#~ " let mut guard = v.lock().unwrap();\n" +#~ " guard.push(40);\n" +#~ " }\n" +#~ "\n" +#~ " println!(\"v: {:?}\", v.lock().unwrap());\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::thread;\n" +#~ "// use std::sync::{Arc, Mutex};\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " let handle = thread::spawn(|| {\n" +#~ " v.push(10);\n" +#~ " });\n" +#~ " v.push(1000);\n" +#~ "\n" +#~ " handle.join().unwrap();\n" +#~ " println!(\"v: {v:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable,compile_fail\n" +#~ "use std::thread;\n" +#~ "// use std::sync::{Arc, Mutex};\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = vec![10, 20, 30];\n" +#~ " let handle = thread::spawn(|| {\n" +#~ " v.push(10);\n" +#~ " });\n" +#~ " v.push(1000);\n" +#~ "\n" +#~ " handle.join().unwrap();\n" +#~ " println!(\"v: {v:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "" +#~ "```rust,editable\n" +#~ "use std::sync::{Arc, Mutex};\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = Arc::new(Mutex::new(vec![10, 20, 30]));\n" +#~ "\n" +#~ " let v2 = Arc::clone(&v);\n" +#~ " let handle = thread::spawn(move || {\n" +#~ " let mut v2 = v2.lock().unwrap();\n" +#~ " v2.push(10);\n" +#~ " });\n" +#~ "\n" +#~ " {\n" +#~ " let mut v = v.lock().unwrap();\n" +#~ " v.push(1000);\n" +#~ " }\n" +#~ "\n" +#~ " handle.join().unwrap();\n" +#~ "\n" +#~ " println!(\"v: {v:?}\");\n" +#~ "}\n" +#~ "```" +#~ msgstr "" +#~ "```rust,editable\n" +#~ "use std::sync::{Arc, Mutex};\n" +#~ "use std::thread;\n" +#~ "\n" +#~ "fn main() {\n" +#~ " let v = Arc::new(Mutex::new(vec![10, 20, 30]));\n" +#~ "\n" +#~ " let v2 = Arc::clone(&v);\n" +#~ " let handle = thread::spawn(move || {\n" +#~ " let mut v2 = v2.lock().unwrap();\n" +#~ " v2.push(10);\n" +#~ " });\n" +#~ "\n" +#~ " {\n" +#~ " let mut v = v.lock().unwrap();\n" +#~ " v.push(1000);\n" +#~ " }\n" +#~ "\n" +#~ " handle.join().unwrap();\n" +#~ "\n" +#~ " println!(\"v: {v:?}\");\n" +#~ "}\n" +#~ "```" + +#~ msgid "You will find solutions to the exercises on the following pages." +#~ msgstr "您可以在以下幾頁查看練習的解決方案。" + +#~ msgid "" +#~ "Feel free to ask questions about the solutions [on GitHub](https://github." +#~ "com/google/comprehensive-rust/discussions). Let us know if you have a " +#~ "different or better solution than what is presented here." +#~ msgstr "" +#~ "歡迎[前往 GitHub](https://github.com/google/comprehensive-rust/" +#~ "discussions)針對解決方案提問。如果您有與本書不同或更好的解決方案,請告訴我" +#~ "們。" + +#~ msgid "" +#~ "**Note:** Please ignore the `// ANCHOR: label` and `// ANCHOR_END: label` " +#~ "comments you see in the solutions. They are there to make it possible to " +#~ "re-use parts of the solutions as the exercises." +#~ msgstr "" +#~ "**注意:**請忽略解決方案中的 `// ANCHOR: label` 和 `// ANCHOR_END: label` " +#~ "註解。之所以有這些註解,是要方便您重複利用解決方案的某些部分來練習。" + +#~ msgid "Day 1 Morning Exercises" +#~ msgstr "第 1 天:上午練習" + +#~ msgid "([back to exercise](for-loops.md))" +#~ msgstr "([返回練習](for-loops.md))" + +#~ msgid "Bonus question" +#~ msgstr "加分題" + +#~ msgid "" +#~ "It requires more advanced concepts. It might seem that we could use a " +#~ "slice-of-slices (`&[&[i32]]`) as the input type to transpose and thus " +#~ "make our function handle any size of matrix. However, this quickly breaks " +#~ "down: the return type cannot be `&[&[i32]]` since it needs to own the " +#~ "data you return." +#~ msgstr "" +#~ "這需要用到更進階的概念。表面上看起來我們可以使用多維度切片 (`&[&[i32]]`) " +#~ "做為轉置的輸入型別,進而讓函式處理任何大小的矩陣。但實際上這很快就會失敗," +#~ "也就是說傳回型別不能是 `&[&[i32]]`,因為它需要擁有您傳回的資料。" + +#~ msgid "" +#~ "You can attempt to use something like `Vec>`, but this doesn't " +#~ "work out-of-the-box either: it's hard to convert from `Vec>` to " +#~ "`&[&[i32]]` so now you cannot easily use `pretty_print` either." +#~ msgstr "" +#~ "您可以嘗試使用 `Vec>` 這類代碼,但這也不能立即見效,因為從 " +#~ "`Vec>` 轉換成 `&[&[i32]]` 並不容易,因此您現在也無法輕易使用 " +#~ "`pretty_print`。" + +#~ msgid "" +#~ "Once we get to traits and generics, we'll be able to use the [`std::" +#~ "convert::AsRef`](https://doc.rust-lang.org/std/convert/trait.AsRef.html) " +#~ "trait to abstract over anything that can be referenced as a slice." +#~ msgstr "" +#~ "一旦瞭解特徵和泛型,我們就能使用 [`std::convert::AsRef`](https://doc.rust-" +#~ "lang.org/std/convert/trait.AsRef.html) 特徵,對任何可當做切片參照的資料進" +#~ "行抽象化。" + +#~ msgid "" +#~ "In addition, the type itself would not enforce that the child slices are " +#~ "of the same length, so such variable could contain an invalid matrix." +#~ msgstr "" +#~ "此外,型別本身不會強制規定子項切片的長度必須相同,因此這類變數可能含有無效" +#~ "的矩陣。" + +#~ msgid "Day 1 Afternoon Exercises" +#~ msgstr "第 1 天:下午練習" + +#~ msgid "([back to exercise](book-library.md))" +#~ msgstr "([返回練習](book-library.md))" + +#~ msgid "Day 2 Morning Exercises" +#~ msgstr "第 2 天:上午練習" + +#~ msgid "([back to exercise](points-polygons.md))" +#~ msgstr "([返回練習](points-polygons.md))" + +#~ msgid "Day 2 Afternoon Exercises" +#~ msgstr "第 2 天:下午練習" + +#~ msgid "([back to exercise](luhn.md))" +#~ msgstr "([返回練習](luhn.md))" + +#~ msgid "([back to exercise](strings-iterators.md))" +#~ msgstr "([返回練習](strings-iterators.md))" + +#~ msgid "Day 3 Morning Exercise" +#~ msgstr "第 3 天:上午練習" + +#~ msgid "([back to exercise](simple-gui.md))" +#~ msgstr "([返回練習](simple-gui.md))" + +#~ msgid "Day 3 Afternoon Exercises" +#~ msgstr "第 3 天:下午練習" + +#~ msgid "([back to exercise](safe-ffi-wrapper.md))" +#~ msgstr "([返回練習](safe-ffi-wrapper.md))" + +#~ msgid "Pattern Matching (TBD)" +#~ msgstr "模式配對 (未定)" + +#~ msgid "Cell/RefCell" +#~ msgstr "Cell/RefCell" + +#~ msgid "" +#~ "Day 1: Basic Rust, syntax, control flow, creating and consuming values." +#~ msgstr "第 1 天:Rust 基本概念、語法、控制流程、建立及取用值。" + +#~ msgid "" +#~ "This slide tries to make the students comfortable with Rust code. They " +#~ "will see a ton of it over the next three days so we start small with " +#~ "something familiar." +#~ msgstr "" +#~ "我們會藉由這張投影片,試著讓學生熟悉 Rust 程式碼。在接下來的三天裡,他們會" +#~ "大量接觸到這些內容,所以我們得從他們熟悉的小地方著手。" + +#~ msgid "" +#~ "In a shell `rustup doc std::fmt` will open a browser on the local std::" +#~ "fmt documentation" +#~ msgstr "" +#~ "在殼層中,`rustup doc std::fmt` 會開啟本機 std::fmt 說明文件上的瀏覽器。" + +#~ msgid "" +#~ "Integer overflow is defined via the [`overflow-checks`](https://doc.rust-" +#~ "lang.org/rustc/codegen-options/index.html#overflow-checks) compile-time " +#~ "flag. If enabled, the program will panic (a controlled crash of the " +#~ "program), otherwise you get wrap-around semantics. By default, you get " +#~ "panics in debug mode (`cargo build`) and wrap-around in release mode " +#~ "(`cargo build --release`)." +#~ msgstr "" +#~ "整數溢位的處理是透過 [`overflow-checks`](https://doc.rust-lang.org/rustc/" +#~ "codegen-options/index.html#overflow-checks) 編譯時間標記定義的。如果啟用的" +#~ "話,程式就會恐慌 (程式受控地異常終止),如未啟用,則會發生語意迴繞現象。根" +#~ "據預設,在偵錯模式 (`cargo build`) 中會發生恐慌,在發布模式 (`cargo build " +#~ "--release`) 中會發生迴繞。" + +#~ msgid "Rust is built with all the experience gained in the last decades." +#~ msgstr "Rust 是根據過去數十年累積的所有經驗打造而成。" + +#~ msgid "" +#~ "Rustdoc comments can contain code snippets that we can run and test using " +#~ "`cargo test`. We will discuss these tests in the [Testing section](../" +#~ "testing/doc-tests.html)." +#~ msgstr "" +#~ "Rustdoc 註解可包含能使用 `cargo test` 執行及測試的程式碼片段。我們會在" +#~ "[「測試」一節](../testing/doc-tests.html)討論這些測試。" + +#~ msgid "" +#~ "Add a static method called `Rectangle::new` and call this from `main`:" +#~ msgstr "新增名為 `Rectangle::new` 的靜態方法,然後從 `main` 呼叫此方法:" + +#~ msgid "" +#~ "While _technically_, Rust does not have custom constructors, static " +#~ "methods are commonly used to initialize structs (but don't have to). The " +#~ "actual constructor, `Rectangle { width, height }`, could be called " +#~ "directly. See the [Rustnomicon](https://doc.rust-lang.org/nomicon/" +#~ "constructors.html)." +#~ msgstr "" +#~ "雖然「技術上」來說,Rust 沒有自訂的建構函式,但靜態方法經常用來初始化結構" +#~ "體 (儘管並非必須)。因此,您可直接呼叫實際的建構函式 `Rectangle { width, " +#~ "height }`。詳情請參閱 [Rustnomicon](https://doc.rust-lang.org/nomicon/" +#~ "constructors.html)。" + +#~ msgid "" +#~ "Add a `Rectangle::square(width: u32)` constructor to illustrate that such " +#~ "static methods can take arbitrary parameters." +#~ msgstr "" +#~ "新增 `Rectangle::square(width: u32)` 建構函式,說明這類靜態方法可以採用任" +#~ "意參數。" + +#~ msgid "" +#~ "The use of the reference `&array` within `for n in &array` is a subtle " +#~ "preview of issues of ownership that will come later in the afternoon." +#~ msgstr "" +#~ "在 `for n in &array` 內使用 `&array` 參照項目是一個巧妙方式,可稍微預示下" +#~ "午將談到的擁有權問題。" + +#~ msgid "Without the `&`..." +#~ msgstr "沒有 `&` 的影響..." + +#~ msgid "" +#~ "The loop would have been one that consumes the array. This is a change " +#~ "[introduced in the 2021 Edition](https://doc.rust-lang.org/edition-guide/" +#~ "rust-2021/IntoIterator-for-arrays.html)." +#~ msgstr "" +#~ "迴圈會是取用陣列的迴圈。這是 [2021 年版導入](https://doc.rust-lang.org/" +#~ "edition-guide/rust-2021/IntoIterator-for-arrays.html)的變更。" + +#~ msgid "" +#~ "An implicit array copy would have occurred. Since `i32` is a copy type, " +#~ "then `[i32; 3]` is also a copy type." +#~ msgstr "" +#~ "會發生隱含陣列複製的情形。由於 `i32` 是複製型別,因此 `[i32; 3]` 也會是複" +#~ "製型別。" + +#~ msgid "The Luhn algorithm," +#~ msgstr "盧恩演算法" + +#~ msgid "An exercise on pattern matching." +#~ msgstr "練習模式配對" + +#~ msgid "" +#~ "Copy the code below to and implement the " +#~ "function." +#~ msgstr "將下方程式碼複製到 ,並實作函式。" + +#~ msgid "" +#~ "Try to solve the problem the \"simple\" way first, using `for` loops and " +#~ "integers. Then, revisit the solution and try to implement it with " +#~ "iterators." +#~ msgstr "" +#~ "使用「for」迴圈和整數,先嘗試以「簡單」的方式解決問題。接著,重新查看解決" +#~ "方案,試著使用疊代器實作。" + +#~ msgid "Stack and Heap Example" +#~ msgstr "堆疊和堆積範例" + +#~ msgid "Storing books and querying the collection" +#~ msgstr "儲存書籍並查詢館藏" + +#~ msgid "Keeping track of health statistics for patients" +#~ msgstr "追蹤病患的健康統計資料" + +#~ msgid "" +#~ "Use this to model a library's book collection. Copy the code below to " +#~ " and update the types to make it compile:" +#~ msgstr "" +#~ "這可用來建立圖書館的館藏模型。請將下列程式碼複製到 ,然後更新型別以利編譯:" + +#~ msgid "`Cell` and `RefCell`" +#~ msgstr "`Cell` 和 `RefCell`" + +#~ msgid "" +#~ "`Cell` is typically used for simple types, as it requires copying or " +#~ "moving values. More complex interior types typically use `RefCell`, which " +#~ "tracks shared and exclusive references at runtime and panics if they are " +#~ "misused." +#~ msgstr "" +#~ "`Cell` 因為需要複製或移動值,通常用於簡單的型別。較複雜的內部型別通常會使" +#~ "用 `RefCell`,可在執行階段和恐慌時追蹤共用和專屬的參照 (如果這些參照遭到濫" +#~ "用的話)。" + +#~ msgid "" +#~ "If we were using `Cell` instead of `RefCell` in this example, we would " +#~ "have to move the `Node` out of the `Rc` to push children, then move it " +#~ "back in. This is safe because there's always one, un-referenced value in " +#~ "the cell, but it's not ergonomic." +#~ msgstr "" +#~ "如果我們在本例中使用 `Cell` 而非 `RefCell`,可能須將 `Node` 移出 `Rc` 才能" +#~ "推送子項,然後再將其移回。您可以放心執行這項操作,因為儲存格中始終有一個未" +#~ "參照的值,但不符人體工學。" + +#~ msgid "" +#~ "To do anything with a Node, you must call a `RefCell` method, usually " +#~ "`borrow` or `borrow_mut`." +#~ msgstr "" +#~ "如要對節點執行任何操作,您必須呼叫 `RefCell` 方法,通常是 `borrow` 或 " +#~ "`borrow_mut`。" + +#~ msgid "" +#~ "Experiment with the code above and then consult the documentation for " +#~ "[`impl IntoIterator for &Vec`](https://doc.rust-lang.org/std/vec/" +#~ "struct.Vec.html#impl-IntoIterator-for-%26'a+Vec%3CT,+A%3E) and [`impl " +#~ "IntoIterator for Vec`](https://doc.rust-lang.org/std/vec/struct.Vec." +#~ "html#impl-IntoIterator-for-Vec%3CT,+A%3E) to check your answers." +#~ msgstr "" +#~ "請用上方的程式碼進行試驗,並參閱 [`impl IntoIterator for &Vec`]" +#~ "(https://doc.rust-lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-" +#~ "%26'a+Vec%3CT,+A%3E) 和 [`impl IntoIterator for Vec`](https://doc.rust-" +#~ "lang.org/std/vec/struct.Vec.html#impl-IntoIterator-for-Vec%3CT,+A%3E) 的說" +#~ "明文件確認答案。" + +#~ msgid "" +#~ "Rust derive macros work by automatically generating code that implements " +#~ "the specified traits for a data structure." +#~ msgstr "" +#~ "Rust 衍生巨集的運作原理是自動產生程式碼,用於實作資料結構的指定特徵。" + +#~ msgid "Move method `not_equals` to a new trait `NotEquals`." +#~ msgstr "將 `not_equals` 方法移至新特徵 `NotEquals`。" + +#~ msgid "Make `Equals` a super trait for `NotEquals`." +#~ msgstr "將 `Equals` 設為 `NotEquals` 的超特徵。" + +#~ msgid "Provide a blanket implementation of `NotEquals` for `Equals`." +#~ msgstr "為 `Equals` 提供 `NotEquals` 的大量實作。" + +#~ msgid "" +#~ "With the blanket implementation, you no longer need `Equals` as a super " +#~ "trait for `NotEqual`." +#~ msgstr "" +#~ "採用大量實作後,您就不再需要使用 `Equals` 做為 `NotEqual` 的超特徵。" + +#~ msgid "" +#~ "We will design a classical GUI library using traits and trait objects." +#~ msgstr "我們將使用特徵和特徵物件設計一個典型的 GUI 程式庫。" + +#~ msgid "" +#~ "We will also look at enum dispatch with an exercise involving points and " +#~ "polygons." +#~ msgstr "我們也會透過點和多邊形的相關練習,探討列舉分派情形。" + +#~ msgid "" +#~ "The return type of the function has to be compatible with the nested " +#~ "functions it calls. For instance, a function returning a `Result` " +#~ "can only apply the `?` operator on a function returning a `Result`. It cannot apply the `?` operator on a function returning an " +#~ "`Option` or `Result` unless `OtherErr` implements " +#~ "`From`. Reciprocally, a function returning an `Option` can only " +#~ "apply the `?` operator on a function returning an `Option`." +#~ msgstr "" +#~ "函式的傳回型別必須與它呼叫的巢狀函式相容。舉例來說,傳回 `Result` " +#~ "的函式只能在傳回 `Result` 的函式上套用 `?` 運算子;無法在傳回 " +#~ "`Option` 或 `Result` 的函式上套用該運算子,除非 " +#~ "`OtherErr` 實作了 `From` 則例外。反之,傳回 `Option` 的函式只能在" +#~ "傳回 `Option` 的函式上套用 `?` 運算子。" + +#~ msgid "" +#~ "You can convert incompatible types into one another with the different " +#~ "`Option` and `Result` methods such as `Option::ok_or`, `Result::ok`, " +#~ "`Result::err`." +#~ msgstr "" +#~ "您可以使用不同的 `Option` 和 `Result` 方法,例如 `Option::ok_or`、" +#~ "`Result::ok`、`Result::err` 等,將不相容的型別轉換為其他型別。" + +#~ msgid "" +#~ "It is good practice for all error types that don't need to be `no_std` to " +#~ "implement `std::error::Error`, which requires `Debug` and `Display`. The " +#~ "`Error` crate for `core` is only available in [nightly](https://github." +#~ "com/rust-lang/rust/issues/103765), so not fully `no_std` compatible yet." +#~ msgstr "" +#~ "對所有不需要是 `no_std` 的錯誤型別來說,實作 `std::error::Error` 是很好的" +#~ "做法,`std::error::Error` 會需要 `Debug` 和 `Display`。`core` 的 `Error` " +#~ "Crate 僅於 [nightly](https://github.com/rust-lang/rust/issues/103765) 提" +#~ "供,因此與 `no_std` 尚未完全相容。" + +#~ msgid "" +#~ "It's generally helpful for them to implement `Clone` and `Eq` too where " +#~ "possible, to make life easier for tests and consumers of your library. In " +#~ "this case we can't easily do so, because `io::Error` doesn't implement " +#~ "them." +#~ msgstr "" +#~ "對這種錯誤型別來說,在可能的情況下實作 `Clone` 和 `Eq` 通常也很有用,不僅" +#~ "有利於程式庫的測試,使用者也會更輕鬆。但在本例中,我們無法輕易這麼做,因" +#~ "為 `io::Error` 並未實作 `Clone` 和 `Eq`。" + +#~ msgid "" +#~ "For this exercise, we suggest using a local dev environment instead of " +#~ "the Playground. This will allow you to run your binary on your own " +#~ "machine." +#~ msgstr "" +#~ "在這個練習中,建議您使用本機開發環境,不要用 Playground。這可讓您在自己的" +#~ "機器上執行二進位檔。" + +#~ msgid "" +#~ "To get started, follow the [running locally](../../cargo/running-locally." +#~ "md) instructions." +#~ msgstr "" +#~ "首先,請按照[在本機執行](../../cargo/running-locally.md)的說明操作。" + +#~ msgid "Pattern matching" +#~ msgstr "模式配對" + +#~ msgid "TBD." +#~ msgstr "未定。"