英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论