package mapx // M 是 map[string]interface{} 的别名 type M map[string]interface{} // New 创建一个空 M func New() M { return M{} } // Set 设置单个键值,支持链式调用 func (m M) Set(key string, value interface{}) M { m[key] = value return m } // SetKV 批量设置键值,可变参数形式 func (m M) SetKV(kvs ...interface{}) M { if len(kvs)%2 != 0 { panic("SetKV 参数必须成对出现") } for i := 0; i < len(kvs); i += 2 { key, ok := kvs[i].(string) if !ok { panic("SetKV 键必须是字符串") } m[key] = kvs[i+1] } return m } // Get 获取值 func (m M) Get(key string) interface{} { return m[key] } // GetString 获取字符串类型 func (m M) GetString(key string) string { if v, ok := m[key]; ok { if s, ok := v.(string); ok { return s } } return "" } // GetInt 获取整数类型 func (m M) GetInt(key string) int { if v, ok := m[key]; ok { switch val := v.(type) { case int: return val case int8: return int(val) case int16: return int(val) case int32: return int(val) case int64: return int(val) case float32: return int(val) case float64: return int(val) } } return 0 } // GetFloat 获取浮点数类型 func (m M) GetFloat(key string) float64 { if v, ok := m[key]; ok { switch val := v.(type) { case float32: return float64(val) case float64: return val case int: return float64(val) case int8: return float64(val) case int16: return float64(val) case int32: return float64(val) case int64: return float64(val) } } return 0 } // GetBool 获取布尔类型 func (m M) GetBool(key string) bool { if v, ok := m[key]; ok { if b, ok := v.(bool); ok { return b } } return false } // Merge 合并另一个 M,后者会覆盖前者同名字段 func (m M) Merge(other M) M { for k, v := range other { m[k] = v } return m }