New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Lint on calling to_owned
on a reference
#78187
Comments
We also might want to consider displaying additional information when an error involves a method with a generic return type. Something like:
|
More generally, this issue is caused by the fact that
Unfortunately, I don't think we can do very much about this in general. The method implemented on |
@Aaron1011 I was confused by this multiple times. I don't think this is a linting problem. Actually, I don't understand how this doesn't result in an error. (in fact, if you don't enforce the type on your example (for |
@omarabid Without the enforced type, struct Foo;
fn print_type<T>(val: T) { println!("{}", std::any::type_name::<T>()) }
fn main() {
let a = &Foo;
let b = a.to_owned();
print_type(b);
} this prints |
The
ToOwned
trait has a blanket impl forT: Clone
. Since references implementClone
, it's possible to call&SomeNonCloneType.to_owned()
- this returns a new reference&SomeNonCloneType
, not an ownedSomeNonCloneType
. This can result in a confusing error message:Here, adding
#[derive(Clone)]
toFoo
makes this code compile, but it's not at all obvious from looking at the error message.We should lint on calling
val.to_owned()
orval.clone()
, whenval
is a reference, and treated as theSelf
type (as opposed to being called on a reference to some non-reference type that implementedClone
). This is very likely a mistake, and in any case can be written more succinctly as*val
The text was updated successfully, but these errors were encountered: