Golang打印结构体总是报未定义错误。

huangapple go评论101阅读模式
英文:

Golang Print structure always report undefined

问题

这是我定义的结构 - 通过一个将 JSON 转换为 Go 结构的工具生成:

type NYTimesNews struct {
    Data struct {
        LegacyCollection struct {
            CollectionsPage struct {
                Stream struct {
                    Edges []struct {
                        Node struct {
                            FirstPublished string `json:"firstPublished"`
                            Headline       struct {
                                Default string `json:"default"`
                            } `json:"headline"`
                            Summary string `json:"summary"`
                            URL     string `json:"url"`
                        } `json:"node"`
                    } `json:"edges"`
                } `json:"stream"`
            } `json:"collectionsPage"`
        } `json:"legacyCollection"`
    } `json:"data"`
}

当我在节点层面迭代响应时,一切都正常工作并且可以打印出来,下面是打印出 Edges 数组中的所有节点的代码:

for i, Node := range data.Data.LegacyCollection.CollectionsPage.Stream.Edges {
    // fmt.Printf("[%d] \n %s \n", i, Node)
    fmt.Printf("[%d] \n %s \n %s\n", i, reflect.TypeOf(Node), Node)
}

输出结果

[0] 
 struct { Node struct { FirstPublished string "json:\"firstPublished\""; Headline struct { Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" } 
 {{2022-05-14T21:17:13.000Z {Turkey Offers to Evacuate Mariupol Fighters Despite Disagreements} Turkey has had a ship waiting for weeks in Istanbul to evacuate those remaining in the Azovstal steel plant, but Ukraine and Russia have not agreed to a plan, a Turkish official said. https://www.nytimes.com/2022/05/14/world/europe/azovstal-evacuation-turkey.html}}
[1] 
 struct { Node struct { FirstPublished string "json:\"firstPublished\""; Headline struct { Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" } 
 {{2022-05-14T16:26:03.000Z {Catalan Pop? Corsican Rock? It’s Europe’s Other Song Contest.} The Liet International, a competition for minority and regional languages, lacks the glitz of Eurovision. But its organizers say it helps keep endangered tongues alive. https://www.nytimes.com/2022/05/14/arts/music/minority-languages-song-contest.html}}

但是当我尝试访问 Node 结构中的单个字段时,出现错误。

修改后的代码:

for i, Node := range data.Data.LegacyCollection.CollectionsPage.Stream.Edges {
    fmt.Printf("[%d] \n %s \n %s -------- \n\n", i, reflect.TypeOf(Node), Node.FirstPublished)
    break
}

输出结果

./getdata-url-nytimes.go:92:80: Node.FirstPublished undefined (type struct{Node struct{FirstPublished string "json:\"firstPublished\""; Headline struct{Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" } has no field or method FirstPublished)

在 Go 结构中使用 Node.FirstPublished 打印字段时出现了问题吗?

英文:

Here is the structure I defined - generated from a json to Go struct tool:

type NYTimesNews struct {
	Data struct {
		LegacyCollection struct {
			CollectionsPage struct {
				Stream struct {
					Edges []struct {
						Node struct {
							FirstPublished string `json:"firstPublished"`
							Headline       struct {
								Default string `json:"default"`
							} `json:"headline"`
							Summary string `json:"summary"`
							URL     string `json:"url"`
						} `json:"node"`
					} `json:"edges"`
				} `json:"stream"`
			} `json:"collectionsPage"`
		} `json:"legacyCollection"`
	} `json:"data"`
}

When I iterate response from my request at the layer of Nodes ,everything works right and can be print out, below are the code of print out all Nodes which is in Edges array

  for i, Node:= range data.Data.LegacyCollection.CollectionsPage.Stream.Edges{
      // fmt.Printf("[%d] \n %s \n", i, Node)
      fmt.Printf("[%d] \n %s \n %s\n", i, reflect.TypeOf(Node),Node)
  } 

Output

[0] 
 struct { Node struct { FirstPublished string "json:\"firstPublished\""; Headline struct { Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" } 
 {{2022-05-14T21:17:13.000Z {Turkey Offers to Evacuate Mariupol Fighters Despite Disagreements} Turkey has had a ship waiting for weeks in Istanbul to evacuate those remaining in the Azovstal steel plant, but Ukraine and Russia have not agreed to a plan, a Turkish official said. https://www.nytimes.com/2022/05/14/world/europe/azovstal-evacuation-turkey.html}}
[1] 
 struct { Node struct { FirstPublished string "json:\"firstPublished\""; Headline struct { Default string "json:\"default\"" } "json:\"headline\""; Summary string "json:\"summary\""; URL string "json:\"url\"" } "json:\"node\"" } 
 {{2022-05-14T16:26:03.000Z {Catalan Pop? Corsican Rock? It’s Europe’s Other Song Contest.} The Liet International, a competition for minority and regional languages, lacks the glitz of Eurovision. But its organizers say it helps keep endangered tongues alive. https://www.nytimes.com/2022/05/14/arts/music/minority-languages-song-contest.html}}

But when I tried to access single fields in Node structure error occured

Code after modify:

  for i, Node:= range data.Data.LegacyCollection.CollectionsPage.Stream.Edges{
    fmt.Printf("[%d] \n %s \n %s -------- \n\n", i, reflect.TypeOf(Node), Node.FirstPublished)
    break
  }

Output

./getdata-url-nytimes.go:92:80: Node.FirstPublished undefined (type struct{Node struct{FirstPublished string "json:"firstPublished""; Headline struct{Default string "json:"default""} "json:"headline""; Summary string "json:"summary""; URL string "json:"url""} "json:"node""} has no field or method FirstPublished)

Anything goes wrong when I use 'doc fieldname' to print a field in a Go structure ?

答案1

得分: 1

你将循环变量命名为Node,但实际上它包含的是类型为Edge的结构体。.Node是你迭代的集合中每个Edge的属性。你需要通过边的.Node字段来访问它,像这样:

  for i, edge := range data.Data.LegacyCollection.CollectionsPage.Stream.Edges {
    fmt.Printf("[%d] \n %s \n %s -------- \n\n", i, reflect.TypeOf(edge.Node), edge.Node.FirstPublished)
    break
  }
英文:

You named loop variable Node but what it really contains is a struct of type Edge. .Node is property of each Edge in the collection you iterate over. You need to access it through edge's .Node field like this instead:

  for i, edge:= range data.Data.LegacyCollection.CollectionsPage.Stream.Edges{
    fmt.Printf("[%d] \n %s \n %s -------- \n\n", i, reflect.TypeOf(edge.Node), edge.Node.FirstPublished)
    break
  }

huangapple
  • 本文由 发表于 2022年5月15日 17:02:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/72246905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定