pub struct ReferenceTreeBuilder;Expand description
Builder for constructing reference trees from search results.
§Rust Book Reference
Chapter 4: Understanding Ownership https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
This builder demonstrates how to work with borrowed data to construct owned data structures efficiently.
Implementations§
Source§impl ReferenceTreeBuilder
impl ReferenceTreeBuilder
Sourcepub fn build(result: &SearchResult) -> ReferenceTree
pub fn build(result: &SearchResult) -> ReferenceTree
Build a reference tree from search results.
Creates a hierarchical tree structure:
- Root: search query text
- Translation: translation file entry
- KeyPath: full translation key
- CodeRef: code reference using the key
- KeyPath: full translation key
- Translation: translation file entry
§Rust Book Reference
Chapter 4.2: References and Borrowing https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
§Educational Notes - Borrowing with &SearchResult
This method signature demonstrates immutable borrowing:
pub fn build(result: &SearchResult) -> ReferenceTree
// ^
// Borrows result, doesn't take ownershipWhy borrow instead of taking ownership?
-
Caller keeps ownership:
ⓘlet result = search_translations("add new")?; let tree = ReferenceTreeBuilder::build(&result); // Borrow // result is still usable here! println!("Found {} entries", result.translation_entries.len()); -
No unnecessary cloning:
- If we took ownership:
build(result: SearchResult) - Caller would need:
build(result.clone())- expensive! - With borrowing:
build(&result)- zero cost!
- If we took ownership:
-
Rust’s borrowing rules ensure safety:
- The reference
&resultis valid for the entire function - We can read all fields:
result.query,result.translation_entries - We cannot modify the data (immutable borrow)
- The original data cannot be moved while borrowed
- The reference
Inside the function:
- We borrow fields:
&result.translation_entries - We clone when we need ownership:
result.query.clone() - We iterate with
.iter()to borrow elements:for entry in &result.translation_entries
Key Insight: Borrowing is Rust’s way of saying “I just need to look at this data temporarily, I don’t need to own it.”