yaml封送拆收器不使用String方法。相反,YAML使用encoding.TextMarshaler和encoding.TextUnmarshaler接口。实际上,所有其他编解码器方案(JSON、XML、TOML等)都使用这些接口来读/写值。因此,如果您为您的类型实现这些方法,您将免费收到所有其他编解码器。 下面是如何为枚举生成human-readable编码的示例:https://go.dev/play/p/pEcBmAM-oZJ type Engine intconst ( engineUnknown Engine = iota // must be first EngineDocker engineDone // must be last)var engineNames []stringvar engineNameToValue map[string]Enginefunc init() { engineNames = []string{"Unknown", "Docker"} engineNameToValue = make(map[string]Engine) for i, name := range engineNames { engineNameToValue[strings.ToLower(name)] = Engine(i) }}func (e Engine)