Anonymous enums?


#1

Two basic ways to make an array of “mixed” items to be printed:

use std::fmt::Display;

enum Thing {
    Int(i32),
    Text(&'static str)
}

fn show_things1(things: &[Thing]) {
    for t in things.iter() {
        match t {
            &Thing::Int(n) => println!("{}", n),
            &Thing::Text(s) => println!("{}", s),
        }
    }
}

fn show_things2(things: &[&Display]) {
    for t in things.iter() {
        println!("{}", t);
    }
}

fn main() {
    let arr1 = [Thing::Int(10), Thing::Text("hello")];
    show_things1(&arr1);

    let arr2: [&Display; 2] = [&10, &"hello"];
    show_things2(&arr2);
}

But just like tuples are sometimes handy when you don’t want/need to define a struct and name all its fields, could anonymous enums be sometimes useful in Rust code?

fn show_things1b(things: &[u32 | &'static str]) {
    for t in things.iter() {
        match t {
            u32(n) => println!("{}", n),
            &'static str(s) => println!("{}", s),
        }
    }
}

fn main() {
    let arr1b: [u32 | &'static str; 2] = [10, "hello"];
    show_things1b(&arr1b);
}

#2

It would surely be a cool feature. Perhaps the appropriate match syntax would be the current @ syntax for simple patterns like your example:

match t {
    n @ u32 => println!("{}", n),
    s @ &'static str => println!("{}", s),
}

As for usefulness… I can’t say I have really missed it, myself, except in perhaps a couple of cases. My enums are often too ambiguous for this, unless I’m just bundling a bunch of types. That said, maybe that’s what people in general do. :slight_smile:


#3

Or take a page from the syntax for embedding types in expression position (since this is embedding types in pattern position):

match t {
    n @ <u32> => ...,
    s @ <&'static str> => ...,
}

Or extend patterns to allow for type ascription (which would be handy in a few places):

match t {
    n: u32 => ...,
    s: &'static str => ...,
}

#4

Oh yes. I’d like to have it. Is there any RFC for this?


#5

There was an anonymous enum RFC using a different syntax:

/cc @canndrew


#6

Yeah, there was an RFC for this but it wasn’t very popular. People thought it added too much weight to the language for not enough benefit and, for now, I agree. By far the most important part of that RFC was turning ! into a type and it now looks like that might be going to happen.

However there is another RFC to enable generically-sized tuples. If that gets implemented then anonymous enums would suddenly become much more useful and it would be worth considering this RFC again.


#7

It’s OK. Anonymous enums aren’t a feature I need particularly :slight_smile: