Iota Enums With String Methods

Define integer enums with iota and give them readable names via String() so logs show labels instead of bare numbers.

GoData Integrity

Code

gosnippet
39 lines
package main

import "fmt"

type Level int

const (
	Debug Level = iota
	Info
	Warn
	Error
)

// String:实现 fmt.Stringer,打印与日志自动可读
func (l Level) String() string {
	switch l {
	case Debug:
		return "DEBUG"
	case Info:
		return "INFO"
	case Warn:
		return "WARN"
	case Error:
		return "ERROR"
	default:
		return fmt.Sprintf("Level(%d)", int(l))
	}
}

func main() {
	for _, l := range []Level{Debug, Info, Warn, Error, Level(9)} {
		fmt.Printf("%d -> %s\n", int(l), l)
	}

	// 用枚举做阈值比较:整数语义仍然可用
	if Error > Warn {
		fmt.Println("error is more severe than warn")
	}
}

What the code does

The snippet is organized around the functions String and main.

Repetition is confined to for _, l := range []Level{Debug, Info, Warn, Error, Level(9)} — the rest of the file is straight-line.

Applying it

Entry signature: func (l Level) String() string

The demo output is labeled (error is more severe than warn), so every line in the printed output names the step that produced it.

Statements that decide the outcome

return fmt.Sprintf("Level(%d)", int(l))
for _, l := range []Level{Debug, Info, Warn, Error, Level(9)} {
	fmt.Printf("%d -> %s\n", int(l), l)
}
return "DEBUG"

Interactive Tools for This Topic

FAQ

What does Iota Enums With String Methods print when run?
Run it as a complete program — the output lines carry labels such as `error is more severe than warn`.