3 ms·
I'm not quite sure where the disconnect is either, but yeah, "should I clone everywhere" or "is cloning everywhere idiomatic" is just one of those models that i
by burntsushi 4y ago
I'm not quite sure where the disconnect is either, but yeah, "should I clone everywhere" or "is cloning everywhere idiomatic" is just one of those models that is useful, but like all models, is invariably wrong in some cases.
Just as one example, consider a function I wrote. It accepts a &str as a parameter. Internally, among other things, it clones that &str into a String. If you asked me whether that was "idiomatic" devoid of any other context, I would say, "probably not? Why not just ask for the String or a Into<String> instead?" But it's not a certainty. Just a likelihood.
But now let's add context. The context is that that function I mentioned is Regex::new. Does that change my answer? You bet your ass it does. Because cloning that pattern string has now turned into a definitively negligible cost. (By many orders of magnitude.) And there is upside to accepting a &str: it's non-generic, a little easier to understand and is unlikely to ever run afoul of type inference. Those aren't huge upsides, but there is actually no downside here because of the context.
As others have pointed out, there is no one-size-fits-all answer to this question. There are models though, and those models (e.g., "don't worry about cloning while you're learning Rust") are very likely to serve you quite well. That might not be every path that everyone learning Rust always takes. But it's a decent bet in my experience.
- tptacek 4y agoThis makes sense! (Also, even if I was deliberately cloning liberally, I'd still pass &str to most things).