-
Notifications
You must be signed in to change notification settings - Fork 13.2k
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
Require that objects can only be made from Sized types. Fixes #18333. #18750
Require that objects can only be made from Sized types. Fixes #18333. #18750
Conversation
a8b86b3
to
f12565c
Compare
f12565c
to
7a372e2
Compare
…xistential, r=nrc In the general case, at least, it is not possible to make an object out of an unsized type. This is because the object type would have to store the fat pointer information for the `self` value *and* the vtable -- meaning it'd have to be a fat pointer with three words -- but for the compiler to know that the object requires three words, it would have to know the self-type of the object (is `self` a thin or fat pointer?), which of course it doesn't. Fixes #18333. r? @nick29581
Would it be possible to relax it such that if I have a reference to a trait, I can make a reference to the trait? Example: trait T {
fn t(&self) -> &T {
&self
}
} |
@mathstuf I'm afraid that is not possible, but you can do this: trait T {
fn t(&self) -> &T where Self: Sized { &self }
} |
That comes up with this error:
|
@mathstuf sorry, my mistake, I didn't notice that you had written
In particular, when you return |
That doesn't work because I can't do this: let my_t: &T = some_ref(s);
my.t(); // since `T` is just a reference, we don't have `Sized` |
@mathstuf well, it depends on what you are trying to do =) I should have made it clear that what I wrote will allow you to make an object if you don't have one already, but it will fail if you may have one already. If you want to support that, it's a bit more annoying. You basically need an operation that applies to the reference as a whole, I think:
The point here is that the first impl doesn't do any coercion (it already has an object), and the second impl does (it has a &U for some sized U). It'd be nice to make this smoother, no doubt. |
My current workaround is: trait T {
fn t<'a>(&'a self) -> SomeStruct<'a> { SomeStruct { t: self._self_ref_hack() } }
fn _self_ref_hack(&self) -> &T;
} |
Back out "internal: Disable rustc test metrics"
In the general case, at least, it is not possible to make an object out of an unsized type. This is because the object type would have to store the fat pointer information for the
self
value and the vtable -- meaning it'd have to be a fat pointer with three words -- but for the compiler to know that the object requires three words, it would have to know the self-type of the object (isself
a thin or fat pointer?), which of course it doesn't.Fixes #18333.
r? @nick29581