面试题答案
一键面试package main
import (
"fmt"
"sync"
)
// FilterAndCollect 过滤并收集符合条件的键值对
func FilterAndCollect(data map[string]map[string]int, result *sync.Map) {
var wg sync.WaitGroup
for userId, userData := range data {
wg.Add(1)
go func(uId string, uData map[string]int) {
defer wg.Done()
for productId, count := range uData {
if count > 5 && len(productId) > 10 {
// 使用sync.Map的Store方法将符合条件的用户ID和商品ID存储到共享结果集中
result.Store(uId, productId)
}
}
}(userId, userData)
}
wg.Wait()
}
你可以使用以下方式调用这个函数:
func main() {
data := map[string]map[string]int{
"user1": {
"product1": 3,
"product123456789012": 6,
},
"user2": {
"product123456789": 4,
"product1234567890123": 7,
},
}
var result sync.Map
FilterAndCollect(data, &result)
// 遍历结果集
result.Range(func(key, value interface{}) bool {
fmt.Printf("UserID: %s, ProductID: %s\n", key, value)
return true
})
}
代码说明
-
FilterAndCollect函数:
- 参数
data
是类型为map[string]map[string]int
的数据结构,即外层键是用户ID,内层键是商品ID,值是购买数量。 - 参数
result
是指向sync.Map
的指针,用于存储符合条件的用户ID和商品ID。 - 使用
sync.WaitGroup
来等待所有的goroutine完成。 - 遍历外层的用户ID和内层的商品ID及购买数量,在goroutine中进行条件判断:购买数量大于5且商品ID长度大于10。
- 如果符合条件,使用
sync.Map
的Store
方法将用户ID和商品ID存储到共享结果集中。
- 参数
-
main函数:
- 初始化一个示例数据
data
。 - 创建一个
sync.Map
实例result
。 - 调用
FilterAndCollect
函数进行过滤和收集。 - 使用
sync.Map
的Range
方法遍历结果集并打印符合条件的用户ID和商品ID。
- 初始化一个示例数据