Go语言 获取特定格式的输出

mrfwxfqh  于 2022-12-25  发布在  Go
关注(0)|答案(1)|浏览(161)

我写了一段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 },
]

有没有办法得到想要的格式输出?

pgky5nke

pgky5nke1#

下面是基本实现。

package main

import(
  "fmt"
)

type data struct {
    id   int
    name string
    age  int
}

func print_data_array(datum []data) {
  fmt.Println("[")
  for _, data := range(datum) {
    fmt.Printf("  %v,\n", format_data_struct(data))
  }
  fmt.Println("]")
}

func format_data_struct(d data) (string) {
  // Note: this does not escape quotes in d.name.
  return fmt.Sprintf(
    `{ %v: %v, %v: "%v", %v: %v }`,
    "id", d.id,
    "name", d.name,
    "age", d.age,
  )
}

func main() {
  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},
  }

  print_data_array(people)
}

相关问题