无法解组 golang 中的嵌套结构

问题描述 投票:0回答:1

我正在尝试解组

Config
结构,但未能成功。有人可以告诉我为什么它不起作用吗?

去游乐场:https://go.dev/play/p/a8oHOLpm0em

package main

import (
    "fmt"

    "github.com/BurntSushi/toml"
)

type Meta struct {
    config  Config   `toml:"config"`
    Include []string `toml:"include"`
    Exclude []string `toml:"exclude"`
}

type Config struct {
    Title   string   `toml:"title"`
    Include []string `toml:"include"`
    Exclude []string `toml:"exclude"`
}

var expected_data = `
include = ["README.md", "LICENSE"]
exclude = ["tests", "docs", "examples", "notebooks"]

[config]
include = ["README.md", "LICENSE"]
exclude = ["tests", "docs", "examples", "notebooks"]
title = "pytorch-forecasting"
`

func main() {

    modfile := Meta{}

    _ = toml.Unmarshal([]byte(expected_data), &modfile)

    fmt.Println("Top level Include: ", modfile.Include)
    fmt.Println("Top level Exclude: ", modfile.Exclude)

    fmt.Println("Include: ", modfile.config.Include)
    fmt.Println("Exclude: ", modfile.config.Exclude)
    fmt.Println("Title: ", modfile.config.Title)
}
go
1个回答
0
投票

导出的标识符

可以导出标识符以允许其他人访问它 包裹。如果满足以下条件,则导出标识符:

标识符名称的第一个字符是 Unicode 大写 字母(Unicode字符类别Lu);并且声明了标识符 在包块中或者它是字段名称或方法名称。所有其他 标识符不会被导出。

所以解决方案是让配置字段以大写字母开头:

type Meta struct {
    Config  Config   `toml:"config"`
    Include []string `toml:"include"`
    Exclude []string `toml:"exclude"`
}

https://go.dev/play/p/qQ4yYdnvs8N

© www.soinside.com 2019 - 2024. All rights reserved.