[Pre-RFC] Sub casting as an operator


#1

I know that the Deref pattern is considered an anti-pattern and that it doesn’t work well with multiple Deref targets (a problem with multiple inheritance anyway).

I was wondering if overloading casting could be a good solution.

trait Cast<T> {
    type output;
    fn cast(in: t) -> output;
}

Basically this would mean that the following is possible. Yes I know that it is more code then just selecting the field. But if for whatever reason you wanted to do dynamic cast selection this would be able to facilitate that.


#2

Downcasting is already possible today in Rust by using a method or function.
Why is overloadable syntax necessary?

By whom? It isn’t as far as I’m concerned. It’s a useful tool to create “smart pointer”-like types.


#3

This list which I have seen reference places. You are correct, not all uses are anti-patterns.

Yes you can have a function but what I am saying is that it might be good idea to have a standard way of doing it.


#4

I don’t understand this trait… did you mean something like AsRef? What would T be in the impl?


#5

The above quote doesn’t mean that Deref itself is an anti-pattern, just that simulating inheritance using Deref is.

Anyway, the standard ways of function-based type conversion are:

  • Deref::deref (as mentioned above, and which already has language support in the form of coercions);
  • AsRef::as_ref (which doesn’t have that and is thus always explicit);
  • Borrow::borrow which has some overlap with as_ref but is specifically designed for conversion between types which are semantically “the same” but one is owned (e.g. String -> &str but not String -> &[u8]);
  • ToOwned::to_owned when the conversion happens from a reference-like type to an owned/value-like type; and
  • From::from / Into::into for many general conversions.

I really don’t think we need yet another one.


#6

I understand that that what you’re saying. What I don’t understand is why? What motivates this? Please understand that “it might be a good idea” on its own, without context, is not a very good reason.


#7

We could trait-ify the as cast operation in some way perhaps…


#8

Which is what I was trying to bring up the first place.


#9

or operator-ify into…


#10

I think into would make sense after I have thought about it for a bit