dict.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Author: simon (ynwdlxm@163.com)
  2. // Date: 2025/9/15 17:00
  3. // Desc: 字典数据结构接口定义
  4. package dict
  5. // Consumer 定义了用于遍历字典的消费者函数类型
  6. // 参数 key 是字典的键
  7. // 参数 value 是字典的值
  8. // 返回值决定是否继续遍历,true表示继续,false表示停止
  9. type Consumer func(key string, value any) bool
  10. // Dict 定义了字典接口,提供了基本的键值对操作方法
  11. type Dict interface {
  12. // Get 根据键获取值
  13. // 参数 key 要查找的键
  14. // 返回值 value 是与键关联的值,ok 表示键是否存在
  15. Get(key string) (value any, ok bool)
  16. // Len 返回字典中键值对的数量
  17. Len() int
  18. // Put 插入或更新键值对
  19. // 参数 key 键
  20. // 参数 value 值
  21. // 返回值 result 表示操作结果:1表示新增,0表示更新
  22. Put(key string, value any) (result int)
  23. // PutIfAbsent 当键不存在时才插入键值对
  24. // 参数 key 键
  25. // 参数 value 值
  26. // 返回值 result 表示操作结果:1表示插入成功,0表示键已存在未插入
  27. PutIfAbsent(key string, value any) (result int)
  28. // PutIfExists 当键存在时才更新键值对
  29. // 参数 key 键
  30. // 参数 value 值
  31. // 返回值 result 表示操作结果:1表示更新成功,0表示键不存在未更新
  32. PutIfExists(key string, value any) (result int)
  33. // Remove 根据键删除键值对
  34. // 参数 key 要删除的键
  35. // 返回值 result 表示操作结果:1表示删除成功,0表示键不存在未删除
  36. Remove(key string) (result int)
  37. // ForEach 遍历字典中的所有键值对
  38. // 参数 consumer 是处理每个键值对的函数,当consumer返回false时停止遍历
  39. ForEach(consumer Consumer)
  40. // Keys 返回字典中所有的键
  41. Keys() []string
  42. // RandomKeys 随机返回字典中的键,可能包含重复键
  43. // 参数 limit 限制返回键的数量
  44. RandomKeys(limit int) []string
  45. // RandomDistinctKeys 随机返回字典中的不重复键
  46. // 参数 limit 限制返回键的数量
  47. RandomDistinctKeys(limit int) []string
  48. // Clear 清空字典中的所有键值对
  49. Clear()
  50. }