April 2026
Intermediate
631 pages
16h 20m
English
Let’s revisit the function that takes ownership in Listing 4.16. The issue with this code is that it consumes vec_1, and therefore, the value is no longer accessible in main.
fn main(){ let vec_1 = vec![1, 2, 3]; takes_ownership(vec_1);}fn takes_ownership(vec: Vec<i32>) { println!("vec is: {:?}", vec);}
Listing 4.16 Function That Takes Ownership
In Section 4.2.1, we mentioned that this issue can be fixed by cloning vec_1. However, cloning creates a new heap allocation, which is inefficient. Moreover, if you examine the function, notice how it only prints the vector passed to it, so it doesn’t need to take ownership of the vector. The function shouldn’t be responsible for deciding when the vector should be cleaned ...
Read now
Unlock full access