3 ms·
One thing that still confuses me about Rust and something I'm not able to brush aside is the fact that as far as I can tell I can't ever be certain when Rust wi
by abraxas 7y ago
One thing that still confuses me about Rust and something I'm not able to brush aside is the fact that as far as I can tell I can't ever be certain when Rust will decide that it needs to copy the underlying data or merely pass a pointer. I don't know the language beyond reading a few chapters of the Rust book but this is something I'm stuck on and I won't invest time in learning the language that removes from my control when I pass data by reference versus pass it by value. The cost of the latter is simply too great in certain scenarios.
Can someone share a good, authoritative source that explains the variable passing semantics of Rust in terms that a C/C++/Java programmer can understand?
- estebank 7y agoI don't understand where your confusion is coming from. If and argument is a borrow, it is being passed by reference. If its ownership is passed, the type is passed by value, and a copy might happen if needed or the same portion of memory will be used if the compiler can avoid the copy. You seem to think you have less control over your allocations than in other languages, but this is not accurate, particularly contrasted to GCd languages.
- abraxas 7y ago> and a copy might happen if needed or the same portion of memory will be used if the compiler can avoid the copy How can I definitively tell which of the two things will happen? Under what conditions will it choose to make a copy instead of passing the address?
- estebank 7y agoScratch that, it is actually a planned feature (I thought llvm was already doing it): https://github.com/rust-lang/rust/issues/13707 https://github.com/rust-lang/rust/issues/13707 The idea is to detect large moves and do a pass by reference, much like Swift does. On my personal roadmap I have detecting these cases and lint against it, suggesting passing the argument as & or &mut as appropriate. That way the performance implications and tradeoffs are visible in the code you write/read.
- deleted 7y ago[deleted]
- steveklabnik 7y agoThere's a few ways to tackle this question: On one level, Rust has no defined ABI, so on some level, the answer to this question is "no way to tell." On another level, Rust doesn't have pass by reference. Like C, everything is pass by value, and pointers are themselves values, sometimes called "pass by value by reference." So semantically, if you pass a value, a value will be passed, and if you pass a reference, a reference will be passed. You have control here. On a third level, like C and C++, Rust may optimize this in whatever way it wants. Your function may get inlined, and there's no passing whatsoever. Large values may be allocated on the parent's stack frame and a pointer may be passed instead.