Get type of an arbitrary expression
Nobody has claimed this yet.
- Dominant language
- Markdown
- Stars
- 6.6k
- Forks
- 1.7k
- Avg merge
- 16h 14m
- Merged PRs (30d)
- 1
Description
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.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the proposed .type syntax, examples, and prior art in this issue, then determine the required language semantics and RFC path. No implementation files or tests are named; done would require an agreed design for compile-time type access and an accepted implementation direction.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100