github.com/qxnw/lib4go@v0.0.0-20180426074627-c80c7e84b925/types/map.ext.go (about) 1 package types 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 type ExtendMap map[string]interface{} 9 10 //NewExtendMap 构建包含扩展函数的 map[string]interface{} 11 func NewExtendMap(mp ...map[string]interface{}) ExtendMap { 12 if len(mp) == 0 { 13 return make(map[string]interface{}) 14 } 15 if len(mp) == 1 { 16 return mp[0] 17 } 18 nmap := make(map[string]interface{}) 19 for _, m := range mp { 20 for k, v := range m { 21 nmap[k] = v 22 } 23 } 24 return nmap 25 } 26 27 //GetString 从对象中获取数据值,如果不是字符串则返回空 28 func (q ExtendMap) GetString(name string) string { 29 if value, ok := q[name].(string); ok { 30 return value 31 } 32 return "" 33 } 34 35 //GetInt 从对象中获取数据值,如果不是字符串则返回0 36 func (q ExtendMap) GetInt(name string) int { 37 if value, ok := q[name].(int); ok { 38 return value 39 } 40 return 0 41 } 42 43 //GetTime 从对象中获取数据值,如果不是字符串则返回0 44 func (q ExtendMap) GetTime(name string) time.Time { 45 if value, ok := q[name].(time.Time); ok { 46 return value 47 } 48 return time.Time{} 49 } 50 51 //GetFloat32 从对象中获取数据值,如果不是字符串则返回0 52 func (q ExtendMap) GetFloat32(name string) float32 { 53 if value, ok := q[name].(float32); ok { 54 return value 55 } 56 return 0 57 } 58 59 //GetFloat64 从对象中获取数据值,如果不是字符串则返回0 60 func (q ExtendMap) GetFloat64(name string) float64 { 61 if value, ok := q[name].(float64); ok { 62 return value 63 } 64 return 0 65 } 66 67 //Has 检查对象中是否存在某个值 68 func (q ExtendMap) Has(name string) bool { 69 _, ok := q[name] 70 return ok 71 } 72 73 //GetMustString 从对象中获取数据值,如果不是字符串则返回空 74 func (q ExtendMap) GetMustString(name string) (string, error) { 75 if value, ok := q[name].(string); ok { 76 return value, nil 77 } 78 return "", fmt.Errorf("不存在列:%s", name) 79 } 80 81 //GetMustInt 从对象中获取数据值,如果不是字符串则返回0 82 func (q ExtendMap) GetMustInt(name string) (int, error) { 83 if value, ok := q[name].(int); ok { 84 return value, nil 85 } 86 return 0, fmt.Errorf("不存在列:%s", name) 87 } 88 89 //GetMustTime 从对象中获取数据值,如果不是字符串则返回0 90 func (q ExtendMap) GetMustTime(name string) (time.Time, error) { 91 if value, ok := q[name].(time.Time); ok { 92 return value, nil 93 } 94 return time.Time{}, fmt.Errorf("不存在列:%s", name) 95 } 96 97 //GetMustFloat32 从对象中获取数据值,如果不是字符串则返回0 98 func (q ExtendMap) GetMustFloat32(name string) (float32, error) { 99 if value, ok := q[name].(float32); ok { 100 return value, nil 101 } 102 return 0, fmt.Errorf("不存在列:%s", name) 103 } 104 105 //GetMustFloat64 从对象中获取数据值,如果不是字符串则返回0 106 func (q ExtendMap) GetMustFloat64(name string) (float64, error) { 107 if value, ok := q[name].(float64); ok { 108 return value, nil 109 } 110 return 0, fmt.Errorf("不存在列:%s", name) 111 }