[Pre-RFC] Sub casting as an operator

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.

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.

1 Like

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.

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

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.


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.

1 Like

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

1 Like

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

or operator-ify into…

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.