4 ms·
There is a Rust idiom that works a little bit like that overloading case: fn eats_a_string(s: impl Into<String>) { dbg!(s.into()); } fn ma
by oconnor663 7y ago
There is a Rust idiom that works a little bit like that overloading case:
fn eats_a_string(s: impl Into<String>) {
dbg!(s.into());
}
fn main() {
eats_a_string("foo");
eats_a_string("foo".to_string());
eats_a_string(&"foo".to_string());
}
In that case, eats_a_string() will allocate internally in the first and third cases, but it won't allocate in the second case, because the caller gives up ownership of its own allocated String. I wouldn't say this is a super common idiom, and "provide only the argument-eating version and rely on the caller to `clone` at their discretion" is often preferred to be simpler and more explicit. But you see it occasionally in the standard library, for example here: https://doc.rust-lang.org/std/ffi/struct.CString.html#method.new https://doc.rust-lang.org/std/ffi/struct.CString.html#method...
- FreeFull 7y agoThis sort of pattern tends to be more useful in case it's something like `CustomString` rather than just a regular `String`, and you still want your function/method to work with regular string literals. Also, other similar usecases, where there's a custom type that can be made from a standard type.