Go语言学习
https://github.com/inancgumus/learngo
24-structs
exercises
01-warmup
package main
import "fmt"
func main() {
type item struct {
id int
name string
price int
}
type game struct {
item // (1)此处的item既是类型,也是字段
genre string
}
games := []game{ // (2)最前面的item和genre可以删除,打印的时候自己一开始用了类似g.item.name这种(两种打印都可以);三个大括号
{
item: item{id: 1, name: "god of war", price: 50},
genre: "action adventure",
},
{item: item{id: 2, name: "x-com 2", price: 40}, genre: "strategy"},
{item: item{id: 3, name: "minecraft", price: 20}, genre: "sandbox"},
}
fmt.Printf("Inanc's game store has %d games.\n\n", len(games))
for _, g := range games {
fmt.Printf("#%d: %-15q %-20s $%d\n",
g.id, g.name, "("+g.genre+")", g.price) // (3)%-15q %-20s
}
}
这是我写的
import "fmt"
func main() {
type item struct {
id int
name string
price int
}
type game struct {
item
genre string
}
games := []game{
{item: item{id: 1, name: "god of war", price: 50}, genre: "action adventure"},
{item: item{id: 2, name: "x-com 2", price: 30}, genre: "strategy"},
{item: item{id: 3, name: "minecraft", price: 20}, genre: "sandbox"},
}
for _, g := range games {
fmt.Printf("%d %#v %d %s\n", g.id, g.name, g.price, g.genre)
}
}

浙公网安备 33010602011771号