我在学古兰语。我正在尝试存储一些数据,然后将这些数据发送到文件。
这个python块的golang等价物是什么?(字典列表)
friends = [
{
"name":"James",
"age":44,
},
{
"name":"Jane",
"age":47,
},
]
使用映射切片还是使用结构更好?
我希望能够过滤数据(例如,所有超过45岁的朋友)并对数据进行排序(假设我有12+记录)。然后打印到屏幕上。
发布于 2017-10-18 16:03:35
在python中使用dict的许多用例,在Go中都需要一个struct来获取静态类型。在您的例子中,这看起来像是一片结构:
type Friend struct{
Name string `json:"name"`
Age int `json:"age"`
}
然后,您可以序列化/反序列化到[]*Person
发布于 2017-10-18 16:57:48
Puuhon的list
等价物是slice
,两者具有相同的语义和用例。
但是在切片中放入什么呢?这取决于你的判断力。如果它们是相同的字段,我建议使用struct
。给它类似上面的字段。例如,有时你必须存储不同的键和不同的字符串值。将其定义为映射到字符串的字符串:
map[string]string
作为最后的手段,有可能生成动态类型的映射。但是不要过度使用它,因为您失去了静态类型的所有好处。程序变得更容易出错,变得更慢。
发布于 2017-10-19 07:33:52
下面是一个小示例程序,它可以完成您想要的操作:
package main
import (
"fmt"
"sort"
)
type friend struct {
name string
age int
}
func main() {
friends := []friend{
{"James", 44},
{"Jane", 47},
{"Bob", 30},
{"Cesar", 90},
{"John", 45},
}
over45 := filterFriends(friends, func(f friend) bool {
return f.age > 45
})
fmt.Println("over 45:", over45)
// note that sort.Sort will change the contents of the slice; if you want
// to keep the original order as well, you would first have to copy that
// slice and sort the copy
sort.Sort(byAge(friends))
fmt.Println("sorted by age:", friends)
}
// filterFriends takes your slice and a predicate to filter by, then returns a
// newly allocated list of friends that made it through the filter.
func filterFriends(friends []friend, pred func(friend) bool) []friend {
var fit []friend
for _, f := range friends {
if pred(f) {
fit = append(fit, f)
}
}
return fit
}
// byAge implements the sort.Interface so we can pass it to sort.Sort.
type byAge []friend
func (f byAge) Len() int { return len(f) }
func (f byAge) Less(i, j int) bool { return f[i].age < f[j].age }
func (f byAge) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
该程序的输出为:
over 45: [{Jane 47} {Cesar 90}]
sorted by age: [{Bob 30} {James 44} {John 45} {Jane 47} {Cesar 90}]
https://stackoverflow.com/questions/46814109
复制相似问题