Skip to content

Tracking Issue for try_as_dyn #144361

Description

@ivarflakstad

View all comments

Feature gate: #![feature(try_as_dyn)]

This is a tracking issue for the try_as_dyn and try_as_dyn_mut functions.

This feature will let us try to turn any value into a dyn MyTrait. If the value does not implement MyTrait then we simply return None so that the user can have some default functionality happen instead.

We expect to be able to remove many cases of specialization from the compiler and instead perform this kind of downcasting in the bodies of functions that were relying on specialization before.

A simple example could be

// Look ma, no `T: Debug`
fn downcast_debug_format<T: 'static>(t: &T) -> String {
    match std::any::try_as_dyn::<_, dyn Debug>(t) {
        Some(d) => format!("{d:?}"),
        None => "default".to_string()
    }
}

Public API

pub const fn try_as_dyn<
    T: Any + 'static,
    U: ptr::Pointee<Metadata = ptr::DynMetadata<U>> + ?Sized + 'static,
>(
    t: &T,
) -> Option<&U>

pub const fn try_as_dyn_mut<
    T: Any + 'static,
    U: ptr::Pointee<Metadata = ptr::DynMetadata<U>> + ?Sized + 'static,
>(
    t: &mut T,
) -> Option<&mut U>

Steps / History

(Remember to update the S-tracking-* label when checking boxes.)

Unresolved Questions

  • Where should these functions live?
    Currently the implementations are in the any module, which can be very confusing as these downcast concepts are for statically known types, while the downcast concepts in Any proper are for dynamic runtime types.
  • try_as_dyn can observe whether a type hidden behind a RPIT implements a trait or not. This makes the opaque/hiding part of opaque types useless. This is hard to avoid because const eval generally reveals opaque types to get layout information
  • Should we have a separate try_as_dyn_static that has a 'static bound and permits turning e.g. a &&'static str into a &dyn Trait even if there is an impl Trait for &'static str, and not a general impl?

Footnotes

  1. https://std-dev-guide.rust-lang.org/feature-lifecycle/stabilization.html

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCF-try_as_dyn`#![feature(try_as_dyn)]`S-tracking-unimplementedStatus: The feature has not been implemented.T-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions