Date Tags rust

Suppose you have a C-Like Enum in Rust like the one below:

enum Foo {
    SomeValue,
    OtherValue
}

Note: C-Like enumerations in Rust have no parameters (i.e. SomeValue(~str)), and can have their discriminator values explicitly set to a constant value (i.e. SomeValue = 0). See http://static.rust-lang.org/doc/master/tutorial.html#enums for details.

If you want to obtain the string value (i.e. "SomeValue") given an unsigned integer, the trick is to first cast it as a Foo value, then use format to obtain its string representation. For the former step, first we need to make Foo implement the CLike trait:

extern mod extra;

use std::cast;
use extra::enum_set::CLike;

#[repr(uint)]
enum Foo {
    SomeValue,
    OtherValue
}

impl CLike for Foo {
    fn to_uint(&self) -> uint {
        *self as uint
    }
    fn from_uint(v: uint) -> Foo {
        unsafe { cast::transmute(v) }
    }
}

The latter step is easy, we just need to format the output as string. The simple way is to make Foo derive from ToStr:

extern mod extra;

use std::cast;
use extra::enum_set::CLike;
use std::to_str::ToStr;

#[repr(uint)]
#[deriving(ToStr)]
enum Foo {
    SomeValue,
    OtherValue
}

impl CLike for Foo {
    fn to_uint(&self) -> uint {
        *self as uint
    }
    fn from_uint(v: uint) -> Foo {
        unsafe { cast::transmute(v) }
    }
}

fn main() {
    let i : Foo = CLike::from_uint(1);
    println!("{}", i.to_str());
}

The output for this code is SomeValue.

Update: Thanks to Manishearth @ irc.mozilla.org for checking out some old links & typos in source code :-)