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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.