As_ref().to_string() et al

I skimmed through a blog a while back that stated that if one is doing:

fn foo<S: AsRef<str>>(s: S) {
  // ...
  let bar = s.as_ref().to_string();
  // ...

(with .as_ref().to_string() being the operative part) then it's a sign one has not understood From and Into.

As it happens, I have a few of those, including .as_ref().to_path_buf() for AsRef<Path> bounds.

Unfortunately I have been unsuccessful in finding that blog post again, but I suspect it was directed at people like myself.

Could someone shed some light on what the issues is, and what one should be doing instead?

If you want to have an owned value anyway, <S: Into<String>> would express this more clearly. It also gets rid of an unnecessary clone if someone calls your method with a String.


The issue is that if someone calls it with S = String, then you will clone it even though there's no need to. The Into<String> trait would not result in a clone of the string.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.