Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang equivalent to list of dicts to store data

Tags:

go

I'm learning golang. I am trying to store a little bit of data, which I will then send to file.

What would be the golang equivalent of this python block? (a list of dicts)

friends = [
  {
    "name":"James",
    "age":44,
  },
  {
    "name":"Jane",
    "age":47,
  },
]

Would it be better to use a slice of maps or a struct?

I want to be able to filter the data (for example all friends over 45) and sort the data (lets imagine I've got 12+ records). then print it to the screen.

like image 497
futureprogress Avatar asked Jan 30 '23 09:01

futureprogress


1 Answers

Many use cases where you use a dict in python, you want a struct for in Go, to get static typing. In your case this looks like a slice of structs to me:

type Friend struct{
  Name string `json:"name"`
  Age  int    `json:"age"`
}

and then you can serialize/deserialize to []*Person

like image 103
captncraig Avatar answered Feb 02 '23 09:02

captncraig