package main
import "fmt"
// 将 int 声明 为 ChipType 芯片类型。
type ChipType int
const (
None ChipType = iota
CPU
GPU
)
// 定义 ChipType 类型的方法 String(), 返回字符串。
func (c ChipType) String() string {
switch c {
case None:
return "None"
case CPU:
return "CPU"
case GPU:
return "GPU"
default:
return "NA"
}
}
func main() {
s := "GPU"
fmt.Printf("%s, %d\n", CPU, GPU)
fmt.Printf("%t", s == GPU.String())
}
使用 String()
方法的 ChipType
在使用上和普通的常量没有区别。当这个类型需要显示为字符串时, Go
语言会自动寻找 String()
方法并进行调用 。