有许多 go 库可简化数据结构遍历,包括:github.com/golang/collections:包含哈希表、堆和队列等数据结构,并提供用于遍历的 foreach 函数。github.com/mitchellh/mapstructure:用于转换数据结构,包含可将非结构化数据解码为结构化数据的 decode 函数。github.com/tidwall/gjson:用于从 json 数据中提取特定元素,包含可返回指定路径处 json 元素的 get 函数。

遍历数据结构的 Golang 库
在 Go 中遍历数据结构是一种常见的任务。有许多库可以简化这一过程,包括:
github.com/golang/collections
立即学习“go语言免费学习笔记(深入)”;
此库提供了大量的数据结构,包括哈希表、堆和队列。它还提供了 ForEach 函数,用于遍历这些结构中的元素。
import "github.com/golang/collections/queue"
func main() {
q := queue.New()
q.Enqueue(1)
q.Enqueue(2)
q.Enqueue(3)
q.ForEach(func(i interface{}) {
fmt.Println(i) // 输出:1 2 3
})
}github.com/mitchellh/mapstructure
此库用于在不同数据结构之间转换。它包含一个 Decode 函数,该函数可将非结构化数据解码为结构化数据。
import "github.com/mitchellh/mapstructure"
func main() {
type Person struct {
Name string
Age int
}
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
}
var person Person
if err := mapstructure.Decode(data, &person); err != nil {
panic(err)
}
fmt.Println(person) // Person{Name:"John Doe", Age:30}
}github.com/tidwall/gjson
此库用于从 JSON 数据中提取特定元素。它包含一个 Get 函数,该函数返回指定路径处的 JSON 元素。
import "github.com/tidwall/gjson"
func main() {
json := `{
"name": "John Doe",
"age": 30
}`
name := gjson.Get(json, "name").String()
age := gjson.Get(json, "age").Int()
fmt.Println(name, age) // John Doe 30
}










