我写了一段go代码,用来过滤包含id、name和age的数据,只有当数据中的age小于21时,才会打印到终端,我使用struct的slice和for循环来得到结果,代码如下:
type data struct {
id int
name string
age int
}
func FilterData() {
var people = []data{
{id: 1, name: "Udin", age: 12},
{id: 2, name: "Wati", age: 51},
{id: 3, name: "Budi", age: 34},
{id: 4, name: "Agus", age: 16},
{id: 5, name: "Sari", age: 19},
{id: 6, name: "Ririn", age: 21},
}
var result = []data{}
for _, item := range people {
if item.age < 21 {
result = append(result, item)
}
}
fmt.Printf("%+v\n", result)
}
func main() {
FilterData()
}
它给出如下输出:
[{id:1 name:Udin age:12} {id:4 name:Agus age:16} {id:5 name:Sari age:19}]
我需要得到一个格式如下的输出:
[
{ id: 1, name: 'Udin', age: 12 },
{ id: 4, name: 'Agus', age: 16 },
{ id: 5, name: 'Sari', age: 19 },
]
有没有办法得到想要的格式输出?
1条答案
按热度按时间pgky5nke1#
下面是基本实现。