Uber 的日志库 Zap 有一个 Config
结构体,其中日志级别定义如下:
type Config struct {
Level AtomicLevel `json:"level" yaml:"level"`
}
其中类型 AtomicLevel
是包装 Go 的 atomic.Int32
的 struct
:
type AtomicLevel struct {
l *atomic.Int32
}
通过此设置,Go 的 json.Unmarshall
如何成功将 string
解码,例如“调试”为正确的原子 int 值,如以下示例所示?
package main
import (
"encoding/json"
"go.uber.org/zap"
)
func main() {
// For some users, the presets offered by the NewProduction, NewDevelopment,
// and NewExample constructors won't be appropriate. For most of those
// users, the bundled Config struct offers the right balance of flexibility
// and convenience. (For more complex needs, see the AdvancedConfiguration
// example.)
//
// See the documentation for Config and zapcore.EncoderConfig for all the
// available options.
rawJSON := []byte(`{
"level": "debug",
"encoding": "json",
}`)
var cfg zap.Config
if err := json.Unmarshal(rawJSON, &cfg); err != nil {
panic(err)
}
logger, err := cfg.Build()
if err != nil {
panic(err)
}
defer logger.Sync()
logger.Info("logger construction succeeded")
}
最佳答案
AtomicLevel 有 UnmarshalText方法,这意味着它实现了encoding.TextUnmarshaler界面。当 JSON 解码器看到 JSON 字符串并且目标是实现 TextUnmarshaler 的类型时,会调用其 UnmarshalText 方法将字符串转换为适当的值(除非该类型实现了 json.Unmarshaler
,在这种情况下优先。AtomicLevel 不优先。)
关于go - Go 如何将字符串解码为包装的原子 int ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72851107/