Re:Should small Rust structs be passed by-copy or by-borrow?
by yeslibertarian on Monday August 26, 2019 @05:53AM
(#20798504)
A good rule is to let the caller decide. If input parameters are by-reference and the caller wants to make them by-reference, congrats, no problem. If caller wants the parameters to by a copy, they can create a clone and pass a reference. But if you impose the input parameters to by copy, there's no way back.
[ Parent
| on HN ]
Re:Should small Rust structs be passed by-copy or by-borrow?
by HereBeBeasties on Monday August 26, 2019 @07:30AM
(#20798922)
Although your point is sort-of true, but I don't really see how it's valid here. The author is talking about the performance implications of the two approaches in situations where the function parameters are not mutated. Suggesting that user "makes the choice" here by taking defensive copies for themselves will probably (but who knows what the optimisers will do - they might just elide it) make performance worse. It's not something end users will think to do, anyway, at least not in the name of performance.
Regardless, I want a library author to help me fall into the pit of performance success, not expect me to do it all for myself.
Re:Should small Rust structs be passed by-copy or by-borrow?
by foldr on Monday August 26, 2019 @07:03AM
(#20798789)
In the case of Rust it would typically be an immutable reference (or else passing by value wouldn't be an alternative). So the caller would have no reason to make a copy.
Re:Should small Rust structs be passed by-copy or by-borrow?
by dthul on Monday August 26, 2019 @08:13AM
(#20799158)
In Rust (end even C++ afaik) it usually makes more sense to let the callee decide. Does it need to own the value? -> Call by value. Does it only need to inspect or (visibly) mutate the value during the function call? -> Call by reference (modulo optimization concerns).
Re:Should small Rust structs be passed by-copy or by-borrow?
by danieldk on Monday August 26, 2019 @09:21AM
(#20799631)
Functions can also be generic over references vs. move/copy semantics, e.g.:
fn foo<T>(frob: T) where T: Borrow<Frob> {
// Do something with frob.borrow()
}
Due to monomorpization, foo is specialized for moves/clones when called as foo(frob) where frob is a value type or for borrows when called as foo(&frob). Similarly, you can use Clone, ToOwned or even Into for going in the opposite direction.Whether such functions are good taste in general is debatable ;).