Hare by Example: Enums

Enums are user-defined types that are a nice way to group related constants together.

use fmt;

// Enum of the cardinal direction on a compass
type direction = enum {
	NORTH,
	SOUTH,
	EAST,
	WEST,
};

// Helper function to convert the enum to a str
fn directionstr(d: direction) str = {
	switch (d) {
	case direction::NORTH =>
		return "North";
	case direction::SOUTH =>
		return "South";
	case direction::EAST =>
		return "East";
	case direction::WEST =>
		return "West";
	};
};

// Enums can have underlying basic types to define values for each one.
type mode = enum u8 {
	READ = 0x00,
	WRITE = 0x01,
};

export fn main() void = {
	const dir = direction::EAST;

	// Get the string version of the direction to print
	fmt::println(directionstr(dir))!;

	// Cast the mode to a u8 to print
	fmt::printf("{}\n", mode::WRITE: u8)!;
};
$ hare run enums.ha
East
1