Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CTFE function for enum types to return the number of variants. #8803

Closed
tikue opened this issue Aug 28, 2013 · 3 comments
Closed

Add CTFE function for enum types to return the number of variants. #8803

tikue opened this issue Aug 28, 2013 · 3 comments

Comments

@tikue
Copy link
Contributor

tikue commented Aug 28, 2013

This would allow for something like this:

enum Foo {
    A,
    B,
}

static two: uint = Foo::len();
assert!(two == 2u);
@thestinger
Copy link
Contributor

This isn't going to happen because we aren't going to add special-cased CTFE functions. Rust doesn't have CTFE beyond syntax extensions. The number of enum variants can be retrieved by via reflection at runtime.

@metajack
Copy link
Contributor

I don't feel super strongly about this, but it has come up at least twice already in Servo. One case was in the profiler where we have a enum for the categories and want to define an array of the size of the number of categories. I think a similar case occurs in rust-mozjs where there are a bunch of object types and we must make sure to get the number of reserved slots right or else things will crash.

How does retrieving the variants at runtime work?

@thestinger
Copy link
Contributor

You can implement the TyVisitor trait and walk the primitives making up a type. It will pass you the number of struct fields or enum variants and their names too.

You can look at what std::repr does for a reasonably complex example. It's how println!("{:?}", x) works.

Although, we could also add intrinsics for this if there's a wide need for it.

xFrednet pushed a commit to xFrednet/rust that referenced this issue May 21, 2022
Fix `cmp_owned` on copy types

fixes rust-lang#8803
fixes rust-lang#7365

changelog: Don't lint `cmp_owned` on `From::from` for copy types
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants