-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Lint against using generic conversion traits when concrete methods are available #36443
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
Comments
Makes sense to me. |
This sounds like a good idea, but I'm not sure what an implementation of this would look like. is the idea just to annotate things like pub fn new<S: AsRef<str>>(somedata: S) -> String {
String::from(somedata.as_ref())
} could be changed to pub fn new<S: AsRef<str>>(somedata: S) -> String {
String::from(AsRef::<str>::as_ref(&somedata))
} This requires no annotations, but I believe it provides the same functionality. One drawback of this approach is that it guides users towards uglier (more verbose) code, but I think this is a worthwhile trade-off, especially considering that veteran users will probably still reach for Edit: Changed the second code block slightly to make it actually compile. |
@cramertj That code is unproblematic and does not need further annotations -- the explicit trait bound The issue is code more like this: |
@bluss The code I used in the example above was reported as causing Either way, a similar recommendation could be made for the example you provided. |
This is not E-easy. |
New lints require an RFC these days; additionally, there's been no comments in two years, so there doesn't seem to be a ton of interest at this time. Closing! |
The standard library's backwards compatibility rules allow the addition of new trait implementations even though this can cause previously working code to hit type inference failures in some contexts. Generic conversion traits (
From
,AsRef
,Borrow
, etc) frequently come up in regression reports since they're commonly implemented multiple times for a given type.Because of this, the standard library commonly provides concrete methods with identical functionality which can be used to avoid these kinds of issues. For example, the
String::into_bytes
method has an equivalent signature to theInto::<Vec<u8>>::into
method onString
.For example, the code in #36352 passed the result of the
Borrow::borrow
method into theFrom::from
method, which failed to type infer after a secondFrom
implementation was added toString
. This could have been avoided if the concrete.as_bytes()
method was used instead of.borrow()
.We should consider adding a lint, probably backed by annotations on the impls, which warn against calling the generic conversion trait methods in concrete contexts when a concrete method is available.
cc @rust-lang/libs
The text was updated successfully, but these errors were encountered: