How does Rust deal with structs as function parameters and return values? -


i have experience in c, i'm new rust. happens under hood when pass struct function , return struct function? seems doesn't "copy" struct, if isn't copied, struct created? in stack of outer function?

struct point {     x: i32,     y: i32, }  // know it's better pass in reference here,  // want clarify point. fn copy_struct(p: point) {      // return value created in outer stack      // won't cleaned while exiting function?       point {.. p}  }  fn test() {     let p1 = point { x: 1, y: 2 };     // p1 copied or copy_struct      // use reference of 1 created on outer stack?     let p2 = copy_struct(p1);  } 

as long time c programmer playing rust recently, understand you're coming from. me important thing understand in rust value vs reference ownership, , compiler can adjust calling conventions optimize around move semantics.

so can pass value without making copy on stack, moves ownership called function. it's still in calling functions stack frame, , c abi perspective it's passing pointer, compiler enforces value never used again upon return.

there's return value optimization, calling function allocates space , pointer passed caller can fill out return value there directly. sort of thing c programmer used handling manually.

so safety of ownership rules , borrow checker, combined lack of fixed guaranteed abi/calling convention, allow compiler generate efficient call sites. , worry more ownership , lifetime, needing try , clever function call stack behavior.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -