-
Notifications
You must be signed in to change notification settings - Fork 13k
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
Consider allowing non-object safe traits as types #42235
Comments
The problem is this: fn foo<T: ?Sized + SomeTrait>() {
T::static_method();
}
fn main() {
foo::<SomeTrait>();
} So, what we could do -- and we discussed this ad infinitum back in the day -- is to keep the current notion of "object-safe", but report an error when:
This was the case at some point. It complicates the "base language" in various ways. For example, right now, MIR has no built-in notion of a "virtual method dispatch". Instead, if you have a variable If you really want trait SomeTrait {
fn non_static_method(&self);
}
impl SomeTrait {
fn static_method();
} Now you can do |
Can you say more about this use case? I don't quite understand. |
(To be clear, though, I am not in particular satisfied with the current setup. I'm just also not very enamored with a setup where |
Wouldn't it be enough to say that the Foo trait object doesn't implement Foo unless it is object safe? I want to call methods from another trait implemented for this trait object (very similar to your example, but polymorphic).
cargonauts has a macro that looks like this: resource MyResource {
method Get in JsonApi;
}
|
Your example demonstrates the problem fine: https://is.gd/LUymxo In order to provide an inherent impl, the trait must be object safe. But I don't think that's necessary. |
@withoutboats argh, I thought I had responded to this, but I see that I didn't. So, would you be satisfied with some solution that permitted methods on non-object-safe trait types, but didn't permit such types to be used more generally? (For example, we might say that you can always have type |
Yes, that seems like exactly what I'm trying for. |
Closing in favor of this RFC rust-lang/rfcs#2027 |
Today, we only allow you to use a trait as a type if that trait is object safe, because you cannot sanely instantiate the object unless the trait is object safe.
This is a bit odd, though! We let you implement traits for
HashMap<f32, _>
, even though you cannot instantiate a HashMap with f32 keys.We could limit the object safety check to two cases:
Similarly, we could allow you to omit associated types from the receiver of such impls (e.g.
impl for Iterator
, without specifying an item).I actually have a motivating use case for this: I have types which are parameterized by a trait, which is used solely for static dispatch. The trait is never actually instantiated as an object, and making it object safe is very limiting.
The text was updated successfully, but these errors were encountered: