My opinion on the "to_owned()" function(s). Not a question, more a debate.

82 points 1668553684

Hey guys! Kind of new to Rust here. There's one thing that's been bugging me lately and I was hoping I could share that here and hear out your opinions on it.

I don't believe the T.to_owned() functions really embody the meaning their names imply. For example, let's look at the signature for &str:

to_owned(&str) -> String

And the version for &[T]:

to_owned(&[T]) -> Vec<T>

Nothing too surprising so far - these are quite common methods to use when you have a slice of something and you want to own it, and the String and Vec types kind of allow you to do that.

Here's my issue: a String isn't really an owned str, just like a Vec<T> isn't really an owned [T]. If you want the data to be transformed into a string or a vector, the to_string() and to_vec() methods exist (respectively). From a to_owned() method, I would expect a signature like this:

to_owned(&str) -> SmartPointer<str>
to_owned(&[T]) -> SmartPointer<[T]>
// or more generally
to_owned(&T) -> SmartPointer<T>
// where
type SmartPointer<T> = Box<T> // or Rc, or Cow, or Arc, etc.

I believe this much more clearly demonstrates and embodies my intent to simply own some piece of data rather than transform it into a container. This may be much less useful than to_string and to_vec, but those functions already exist to serve that purpose.

For this reason, I personally use avoiding to_owned whenever I can help it, because I feel like the name is misleading as to what the function is actually doing.

For clarification, I'm not advocating for changing this: it's a minor issue and something that would cause far more chaos to change than just keeping it the way it is. I guess what I'm really saying is, "If I could re-write the standard library myself, I would implement this trait differently or eliminate it altogether in favor of the to_string(), to_vec(), etc. alternatives."

Thanks for bearing with me, I know this is kind of a weird thought and not really practical as much as it is... philosophical?


Edit: Personally, I have found
/u/KhorneLordOfChaos
(comment link)
and
/u/CocktailPerson's
(comment link)
comments to be the most convincing.

Posting it here so that others can check those out if they want.