Interesting idea.  I'm generally in favor of moving things out of the core language.  What makes me hesitate a bit here is that it would be nice if one could translate C types into Rust types that are then representation-compatible so as to ease interoperability.  If we take this proposal, any C enum would have to be translated into a Rust type that uses an integer instead of an enum.  This means that you'd have to "cast from" this integer any time you wanted to use the relevant field.  Of course, maybe that's better, particularly since some uses of C enums (like bitsets) can't be accommodated by Rust enums.

One correction, though: I believe that, today, you can cast to any numeric type, not only ints.


Niko



March 1, 2013 12:18 AM
Hi everyone,

There is currently a feature whereby custom enum variant discriminants can be specified:

    pub enum Foo {
         Bar = 1,
         Baz = 2,
         Boo = 3,
    }

The sole use of this is casting from the enum to an int:

    println(fmt!("%d", Bar as int)); // prints 1

This feature currently doesn't really meet people's needs. Chief among the issues are:

1. Only ints are supported, but many enums want to correspond to different sizes of types.

2. Only casting *from* an enum value is supported, not casting *to* an enum value. Casting to an enum value is not supported because this is a partial operation.

3. There is no way to have multiple values correspond to a single enum variant.

We could extend the syntax to support these in some way, but I'm personally leaning toward just moving the machinery into a syntax extension. You could write something like:

    numeric_enum!(Foo : uint {
        Bar = 1,
        Baz = 2 | 3,
        Boo = 4
    })

Then the compiler would generate functions like:

    Foo::from_uint(uint) -> Result<Foo,()>
    Foo::to_uint(self) -> uint

One could also imagine a similar syntax extension for bitfields.

Besides the obvious advantage that it simplifies the language, we can make the `from_foo` type return a proper Result (or use the condition system) without building Result into the compiler.

Thoughts?

Patrick
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to