DispatchFromDyn: require additional checks by dingxiangfei2009 · Pull Request #149068 · rust-lang/rust (original) (raw)
Quote @theemathas
@dingxiangfei2009 Your comment in the code unfortunately does not answer my latest comment in this PR. My comment does not involve a double pointer indirection.
I don't think my text articulates my thoughts right. &Outer<T> -> &Outer<U> is not a double pointer indirection, true, and the point is that there are too many "indirection"s.
Maybe I should reword it. The pre-requisite of a valid DispatchFromDyn relation from a type A to a type B is that
AandBare of the same shape, sharing the same concrete type constructor, excluding aliases and genericsAandBare both generic over two distinct type parameterTandUrespectivelyT: Unsize<U>- Most importantly, the "downcast" of a value of
Bback toAis supported. Here we can give an exhaustive list of supported "downcasts" and we can add more as supported types grow.A := &TfromB := &U, orA := &mut TfromB := &mut U
* This works today by dispatching the call to the corresponding method after transparently discarding the metadataA := Adt<T>fromB := Adt<U>whenT: DispatchFromDyn<U>andAdt<_>is reasonable
* This works today by delegating the dispatch to the only field inAafter transparently discarding the metadata
The last bullet point will answer the important question...
Should it?
... which is no, because we don't know how to "downcast" &Outer<U> back to &Outer<T> because that metadata is actually behind one layer of "indirection." The argument against &mut Outer<U> back to &mut Outer<T> case should run like this. The "downcast" mutation would need to leave the address unchanged and, in turn, necessitate mutation of the data behind this &mut borrow. The transformation is no longer transparent and actually would change type of the place behind that borrow. I don't see a way to support it in Rust.
The A := &T case, on the other hand, has no indirection because the metadata is directly attached to the &U pointer. So this "downcast" is simple for us to implement.
I hope that this would be a better answer to the earlier question. I am not sure how much this content could go into the documentation. Please advise.