You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

go-toml Marshal失败:嵌套结构体序列化后生成空文件求助

问题

编写了一段Go程序,尝试将带有toml标签的嵌套结构体进行Marshal操作并写入文件。程序未返回任何错误,结构体打印结果正常,但生成的config.toml文件为空。

程序输出:

[]
{testServer {/var/www} {/tmp} [{testPolicy [10 20 30] [2 2 3]}]}

程序代码:

package main

import (
    "fmt"
    "io/ioutil"
    "log"

    "github.com/pelletier/go-toml/v2"
)

type source struct {
    path string `toml:"path"`
}

type target struct {
    path string `toml:"path"`
}

type policy struct {
    policyName   string `toml:"policyName"`
    schemaDays   []int  `toml:"schemaDays"`
    schemaCounts []int  `toml:"schemaCounts"`
}

type servers struct {
    serverName string   `toml:"serverName"`
    source     source   `toml:"source"`
    target     target   `toml:"target"`
    policies   []policy `toml:"policies"`
}

func main() {

    var s servers = createConfiguration()
    b, err := toml.Marshal(s)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(b)
    err = ioutil.WriteFile("config.toml", b, 0644)
    if err != nil {
        panic(err)
    }
    fmt.Println(s)

}

func createConfiguration() (server servers) {
    s := source{
        path: "/var/www",
    }
    t := target{
        path: "/tmp",
    }
    d := []int{10, 20, 30}
    c := []int{2, 2, 3}
    p := &policy{
        policyName:   "testPolicy",
        schemaDays:   d,
        schemaCounts: c,
    }
    server = servers{
        serverName: "testServer",
        source:     s,
        target:     t,
        policies:   []policy{*p},
    }
    return
}
原因分析

核心问题是Go结构体字段的可见性规则:只有首字母大写的字段才是导出字段(包外可访问),而go-toml这类序列化库只能处理导出字段。

你代码里所有结构体的字段都是小写开头(比如source.path、policy.policyName),属于包私有字段,toml.Marshal根本读不到这些字段的值,所以序列化后得到的是空字节数组(也就是你看到的输出[]),写入文件自然就是空的。

解决办法

把所有需要序列化的结构体字段首字母改成大写,同时保留原有的toml标签即可:

type source struct {
    Path string `toml:"path"`
}

type target struct {
    Path string `toml:"path"`
}

type policy struct {
    PolicyName   string `toml:"policyName"`
    SchemaDays   []int  `toml:"schemaDays"`
    SchemaCounts []int  `toml:"schemaCounts"`
}

type servers struct {
    ServerName string   `toml:"serverName"`
    Source     source   `toml:"source"`
    Target     target   `toml:"target"`
    Policies   []policy `toml:"policies"`
}

修改后重新运行程序,就能生成内容正确的config.toml文件了。

内容的提问来源于stack exchange,提问作者learning-man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:24:54