-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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
Suggest converting a type to trait object when it's possible and the method expects one #42499
Comments
It's unnecessary to cast. A simple coercion will do the job if no generics are involved. The problem in your case is that there's no way to convert |
First of all, if the API is not mine, so I can hardly do anything for it. Secondly, maybe @sfackler who is the author of the API in this example (the postgres crate), has something to say, but I think taking trait objects may be unavoidable in cases like heterogenous lists, so diagnostics in such cases are not a non-issue. Indeed, as you say, there's no way to convert |
The API takes a slice because it was defined quite a long time ago - probably before |
So, what's the state of this issue? Is there an actual change to be made here? |
We should do two things as suggested in the original post:
|
@oli-obk we now suggest the constraining of type params with a trait bound, but there are a couple of cases that aren't totally handled:
|
If the method explicitly expects a trait object, such as
&postgres::types::ToSql
, (ToSql
is a trait), and the user is trying to pass it a type that implements the trait, such asString
, it's likely that the user either doesn't understand the distinction between trait object and trait bounds in generics, or has accidentally missed that the function isn't expecting a generic type but a trait object.In this case, it would be helpful to show a more specific error message than the standard "type mismatch". The standard error message is like this:
First of all, "expected trait" is downright misleading, I think it should be "expected trait object". Secondly, it would be helpful to show a hint that says that:
String
implements traitToSql
, but this method is expecting a trait object, not any type that implements the trait.&String
withvalue as &postgres::types::ToSql
.The text was updated successfully, but these errors were encountered: