登录
首页 >  Golang >  Go问答

Go 如何将字符串解组为包装的atomc int?

来源:stackoverflow

时间:2024-04-14 14:21:32 448浏览 收藏

本篇文章给大家分享《Go 如何将字符串解组为包装的atomc int?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

uber 的日志库 zap 有一个 config 结构体,其中日志级别定义如下:

type config struct {
    level atomiclevel `json:"level" yaml:"level"`
}

其中类型 atomiclevel 是包装 go 的 atomic.int32struct

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 不会) t.)

终于介绍完啦!小伙伴们,这篇关于《Go 如何将字符串解组为包装的atomc int?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>