go 为整数常量添加 String() 方法

package main

import "fmt"

type State int

const (
	Unknown State = iota
	NotStart
	Processed
	Stopped
	Terminated
)

func (p State) String() string {
	switch p {
	case NotStart:
		return "NotStart"
	case Processed:
		return "Processed"
	case Stopped:
		return "Stopped"
	case Terminated:
		return "Terminated"
	default:
		return "Unknown"
	}
}

func main() {
	status := State(1)
	statusMsg := status.String()
	fmt.Println(statusMsg)

	status = State(5)
	statusMsg = status.String()
	fmt.Println(statusMsg)
}

 

你可能感兴趣的:(go)