Skip to content

Get type of an arbitrary expression #2704

@nvzqz

Description

@nvzqz

It would be very useful in certain contexts (such as macros) to be able to get the concrete type of some variable through a given binding.

The idea for the syntax came from the upcoming .await syntax. Since this sets the precedent of having reserved keywords in a property position, I think that this would fit well. However, I understand that—unlike ? and .await.type acts more as an accessor instead of a control flow construct. Depending on one's point of view, this may be a good thing since it aligns somewhat with how property accessors appear today.

Examples

It would work as follows:

let x = 20;

// Equivalent to `typeof(x) y = x;` in C
let y: x.type = x;

type X = x.type;

static_assertions::assert_eq_type!(x.type, i32);

How it may be used within a macro:

macro_rules! do_stuff {
    ($x:expr) => {
        let y = <$x.type>::new(/* ... */);
        $x.do_stuff_with(y);
    }
}

Currently, the only way of getting the "type" of a binding within the context of a macro doesn't allow for the above code to work. For example:

macro_rules! do_stuff {
    ($x:expr) => {
        fn with_type_of<T>(x: T) {
            let y = T::new(/* ... */);
            x.do_stuff_with(y);
        }
        with_type_of($x);
    }
}

Prior art

In C, there's typeof(), which this feature would be an exact parallel to.

In Swift, there's type(of:), which returns a runtime value with metadata for the type of a value. This is different in that this proposed x.type would only be usable within a compile-time type context, not a runtime one.

For those who want to go spelunking into other languages, there's a typeof Wikipedia article.

Why I want this

It would make the implementation of assert_eq_size_val a bit less awkward.

I can also get more imaginative about use cases outside of the given examples upon request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-typesystemType system related proposals & ideasT-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions