Expand description
§Ownership and Borrowing - Rust Book Chapter 4
This module demonstrates ownership, borrowing, and references from The Rust Book Chapter 4.
§Key Concepts Demonstrated
-
Borrowing with
&References (Chapter 4.2)- The
build()method takes&SearchResultinstead ofSearchResult - Allows reading data without taking ownership
- Multiple borrows can exist simultaneously for reading
- The
-
Ownership Transfer with
.clone()(Chapter 4.1)result.query.clone()creates a new ownedString- Necessary when building nodes that need to own their data
- Trade-off: memory cost vs. ownership flexibility
-
Iterators and Borrowing (Chapter 4.2 + 13.2)
.iter()creates an iterator of references (&T)- Allows processing collections without taking ownership
- The original collection remains usable after iteration
-
References in Collections (Chapter 4.2)
Vec<_>with.iter()createsVec<&T>- Temporary collections of references avoid cloning
- References must not outlive the data they point to
§Learning Notes
Why use &SearchResult instead of SearchResult?
- Caller retains ownership and can reuse the data
- More efficient - no need to clone the entire structure
- Follows Rust convention: borrow when you don’t need ownership
When to clone vs. when to borrow?
- Clone: When you need to store data in a new structure (like TreeNode)
- Borrow: When you only need to read data temporarily
The .iter() pattern:
ⓘ
for entry in &result.translation_entries { // Borrows each element
// entry is &TranslationEntry
}
// vs
for entry in result.translation_entries { // Takes ownership
// entry is TranslationEntry (moved)
}Structs§
- Reference
Tree Builder - Builder for constructing reference trees from search results.