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

Go语言中静态数据加载到嵌套结构体的语法问题求助

问题分析与修正代码

你的代码存在几个关键问题,导致无法正确初始化结构体:

1. JSON标签格式错误

Tag结构体的JSON标签写法有误,标签内的空格和逗号位置不符合规范,正确格式应为json:"字段名,omitempty",多余空格会导致JSON编解码失效。

2. 切片初始化语法错误

Tags字段是[]Tag类型(Tag切片),你错误地用Tag{}包裹数组,还使用了类似JSON对象的语法初始化结构体。Go中结构体切片的正确初始化方式是用[]Tag{}直接包裹多个Tag实例,每个实例通过字段名赋值。

3. 未定义类型错误

读取文件时声明了var fromFile Person,但代码中从未定义过Person类型,应替换为你定义的Stack类型。


修正后的完整代码

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    type Tag struct {
        AppID    string `json:"appID,omitempty"`
        Category string `json:"category,omitempty"`
    }

    type Stack struct {
        Reputation   int    `json:"reputation"`
        UserID       int    `json:"user_id"`
        UserType     string `json:"user_type"`
        ProfileImage string `json:"profile_image"`
        DisplayName  string `json:"display_name"`
        Link         string `json:"link"`
        Tags         []Tag  `json:"tags"`
    }

    toFile := Stack{
        Reputation:   141,
        UserID:       9820773,
        UserType:     "registered",
        ProfileImage: "https://graph.facebook.com/10209865263541884/picture?type=large",
        DisplayName:  "Joe Smith",
        Link:         "https://stackoverflow.com/users/9820773/joe-smith",
        Tags: []Tag{
            {AppID: "go", Category: "backend"},
            {AppID: "fiber", Category: "framework"},
        },
    }

    // 写入文件
    tmpFile, err := ioutil.TempFile(os.TempDir(), "sample-")
    if err != nil {
        panic(err)
    }
    defer os.Remove(tmpFile.Name())
    err = json.NewEncoder(tmpFile).Encode(toFile)
    if err != nil {
        panic(err)
    }
    err = tmpFile.Close()
    if err != nil {
        panic(err)
    }

    // 读取文件
    tmpFile2, err := os.Open(tmpFile.Name())
    if err != nil {
        panic(err)
    }
    var fromFile Stack
    err = json.NewDecoder(tmpFile2).Decode(&fromFile)
    if err != nil {
        panic(err)
    }
    err = tmpFile2.Close()
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", fromFile)
}

内容的提问来源于stack exchange,提问作者Robert Campbell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:41:04