在Go对象上打印嵌套字段

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

Printing nested fields on Go objects

问题

我正在尝试理解下面的代码,如何打印出"species"和"width"键的值。

package main

import (
	"encoding/json"
	"fmt"
)

type Dimensions struct {
	Height int
	Width  int
}

type Bird struct {
	Species     string
	Description string
	Dimensions  Dimensions
}

func main() {
	birdJson := `{"species":"pigeon","description":"likes to perch on rocks", "dimensions":{"height":24,"width":10}}`
	var bird Bird
	json.Unmarshal([]byte(birdJson), &bird)
	fmt.Println(bird.Species, bird.Dimensions.Width)
	// 输出结果:pigeon 10
}

我期望的输出是:pigeon 和 10

英文:

I'm trying to understand from the below code, how can I print only "species" and "width" key values.

package main

import (
	"encoding/json"
	"fmt"
)

type Dimensions struct {
	Height int
	Width  int
}

type Bird struct {
	Species     string
	Description string
	Dimensions  Dimensions
}

func main() {
	birdJson := `{"species":"pigeon","description":"likes to perch on rocks", "dimensions":{"height":24,"width":10}}`
	var bird Bird
	json.Unmarshal([]byte(birdJson), &bird)
	fmt.Println(bird)
	// {pigeon likes to perch on rocks {24 10}}
}

The output I'm expecting is: pigeon and 10

答案1

得分: 3

你在这里的做法是打印整个对象,而你应该打印你要查找的特定字段。相反,你应该尝试这样做:

fmt.Println(bird.Species, bird.Dimensions.Width)

这将输出:

鸽子 10

为了使输出更易读,你可以使用fmt.Printf,像这样:

fmt.Printf("物种:%s,宽度:%d\n", bird.Species, bird.Dimensions.Width)

这将输出:

物种:鸽子,宽度:10

英文:

What you're doing here is printing the entire object when you should be printing the specific fields you're looking for. Instead, you should try this:

fmt.Println(bird.Species, bird.Dimensions.Width)

which will yield:

> pigeon 10

To make this a bit more readable, you can use fmt.Printf like so:

fmt.Printf("Species: %s, Width: %d\n", bird.Species, bird.Dimensions.Width)

which will yeild:

> Species: pigeon, Width: 10

huangapple
  • 本文由 发表于 2022年11月25日 16:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/74569772.html
匿名

发表评论

匿名网友

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

确定