我正在学习golang。我正在尝试存储一点数据,然后将其发送到文件。
这个蟒蛇块的戈朗等价物是什么?(字典列表)
friends = [
{
"name":"James",
"age":44,
},
{
"name":"Jane",
"age":47,
},
]
使用地图切片还是结构更好?
我希望能够过滤数据(例如所有45岁以上的朋友)并对数据进行排序(假设我有12+条记录)。 然后将其打印到屏幕上。
许多用例,你在python中使用字典,你想要一个结构在Go中,以获得静态类型。在您的情况下,这对我来说看起来像是一段结构:
type Friend struct{
Name string `json:"name"`
Age int `json:"age"`
}
然后你可以序列化/反序列化以[]*Person
Puuhon的list
等价物是一个slice
,两者都有相同的语义和用例。
但是放什么切片呢?这取决于你的字典。如果它们是相同的字段,我建议使用 struct
s。给它像上面这样的字段。例如,有时您必须存储不同的键和不同的字符串值。将其定义为映射字符串到字符串:
map[string]string
作为最后的手段,有可能制作动态类型地图。但这并不是过度使用它,因为您失去了静态类型的所有好处。程序变得更加容易出错且速度变慢。
这里有一个小示例程序,可以执行您想要的操作:
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}]
鉴于您的示例数据似乎是同质的(朋友共享他们的属性),您可以使用 struct
s 的slice
,如下所示:
type Friend struct {
Name string
Age int
}
var friends []Friend = make([]Friend, 0)
现在,假设您已经将朋友添加到该切片中,则可以使用大于某个数字的Age
来过滤它们:
func filterFriendsAboveAge(allFriends []Friend, minAge int) []Friend {
results := make([]Friend, 0)
for _, friend := range allFriends {
if friend.Age > minAge {
results = append(results, friend)
}
}
return results
}
请注意,通过调用此函数,返回的切片中的 Friend 值将是原始切片的副本。如果需要保留标识,请改用指针。