登录
首页 >  Golang >  Go问答

在 toml 文档中查找未解码的值

来源:stackoverflow

时间:2024-02-12 16:30:26 330浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《在 toml 文档中查找未解码的值》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在使用 burntsushi 的 go 解析器(https://godocs.io/github.com/burntsushi/toml)并按照他的示例来取消解码值,似乎我无法取消解码 a 内的 toml 文档哈希表查找意外添加的额外键。

官方文档,解释如何解码 toml 文档以查找任何额外的键 (https://godocs.io/github.com/burntsushi/toml#metadata.undecoded) 按照上面的例子,我只是想确保哈希表也是正确的:

var blob = `
    [kiwi]
        key1 = "value1"
        key2 = "value2"
        key3 = "value3"
    `

var conf struct {
    Key1 string
    Key3 string
}
md, err := toml.Decode(blob, &conf)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Undecoded keys: %q\n", md.Undecoded())

// Desired output
// Undecoded keys: ["kiwi.key2"]

// Actual output
// Undecoded keys: ["kiwi" "kiwi.key1" "kiwi.key2" "kiwi.key3"]

如何将哈希表 [kiwi] 表示为 conf 结构?

前往演示链接: https://go.dev/play/p/uhkbcedwkg_p

感谢您的阅读,感谢任何帮助。


正确答案


最后使用以下结构,它只会成功检查表名称:

type config struct {
        kiwi struct {
           key1 string
           key3 string
        }
    }
    var conf config
    md, err := toml.decode(blob, &conf)
    if err != nil {
        panic(err)
    }
    fmt.printf("undecoded keys: %q\n", md.undecoded())

https://github.com/BurntSushi/toml/blob/master/_example/example.toml

type kiwi struct {
    Key1 string
    Key3 string
}

func main() {
    var blob = `
    [kiwi]
        key1 = "value1"
        key2 = "value2"
        key3 = "value3"
    `
    var conf map[string]kiwi
    md, err := toml.Decode(blob, &conf)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Undecoded keys: %q\n", md.Undecoded())

    //Undecoded keys: ["kiwi.key2"]  

}

以上就是《在 toml 文档中查找未解码的值》的详细内容,更多关于的资料请关注golang学习网公众号!

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