Closed u2 closed 5 years ago
FYI, I am a little confused about memory management when pass a struct param to function and get struct return value. I did some search and this is a brief summary:
fn init_array() -> [u32; 256] {
[!0; 256]
}
let array = init_array();
Will be optimized to something like this:
fn init_array(array: &mut [u32; 256]) {
*array = [!0; 256];
}
let mut array = unsafe { mem::uninitialized() };
init_array(&mut array);
refs:
Rust is a Pass-by-value language, it always copies the value in the stack. For the copy
type, the real value stores in the stack, for the clone
there is a struct in the stack, the data part stores in the heap.
Use an explicit clone in
ExtensionNode::new
. Use an explicit clone inLeafNode::new
,value.to_vec()
is a implicit clone. Use an explicit clone inNibbles::from_hex
.If in the function signature we use reference and inside the function body we clone the reference content, it's better we pass the real content in.
eg:
a better way is
There are two reasons: