[golang]字符串类型转换的封装
在处理url参数时,你是否会因为要经常将字符串类型转换为其他类型,而感觉到代码冗长,麻烦?这里推荐一个字符串封装库,具体实现非常简单,可到liamylian/values查看,下面给出用法:
import "github.com/liamylian/values" var v values.Value // 设置默认值,如果为空则使用默认值 v = values.Value("") d := v.Default("happy").String() // 空值判断 v = values.Value("") isEmpty := v.IsEmpty() // 类型转换 v = values.Value("1") s := v.String() b, err := v.Bool() f32, err := v.Float32() f64, err := v.Float64() i, err := v.Int() u, err := v.Uint() i8, err := v.Int8() u8, err := v.Uint8() i16, err := v.Int16() u16, err := v.Uint16() i32, err := v.Int32() u32, err := v.Uint32() i64, err := v.Int64() u64, err := v.Uint64()
import "github.com/liamylian/values" var v Strict // 是否为nil v = NewStrict(nil) b := v.IsNil() // 默认值 v = NewStrict(nil) i := v.IfNil("abc").Interface() // 获取值 s, ok := v.MustString() b, ok := v.MustBool() f32, ok := v.MustFloat32() f64, ok := v.MustFloat64() i, ok := v.MustInt() u, ok := v.MustUint() i8, ok := v.MustInt8() ui8, ok := v.MustUint8() i16, ok := v.MustInt16() u16, ok := v.MustUint16() i32, ok := v.MustInt32() u32, ok := v.MustUint32() i64, ok := v.MustInt64() u64, ok := v.MustUint64()
除此之外包里还对map[string]string做了一层封装,即Values类型。因为底层使用了sync.Map,所以保证了线程安全,读写不用加锁。用法如下:
import "github.com/liamylian/values" // 从map创建 m := map[string]Value{"foo": "bar"} vs := values.FromMap(m) // 转换成map vs.ToMap() // json序列号与反序列化 bytes, _ :=json.Marshal(vs) json.Unmarshal([]byte(`{"foo":"bar","int":1,"bool":true}`), &vs) // 获取值 value, exists := vs.Get("foo") // 设置值 vs.Set("earth", "moon") // 删除值 vs.Delete("foo") // 批量设置值 m = map[string]Value{"bar": "foo", "moon":"earth"} vs.Sets(m) // 遍历 vs.Range(func(key string, value Value) bool { fmt.Println("%s: %s", key, value) return true })
相关推荐
songshijiazuaa 2020-09-01
Biao 2020-08-20
tomson 2020-06-26
Wmeng0 2020-06-14
choupiaoyi 2020-05-29
willowwgx 2020-05-18
yunfeitian 2020-04-18
zuihaobushi 2020-04-08
TreasureZ 2020-03-27
nxcjh 2020-02-19
ALiDan 2020-02-01
lmseohy 2020-01-13
waiwaiLILI 2020-01-12
xiaoxiaoCNDS 2020-01-08
ITxiaobaibai 2020-01-01
lxjhoney 2011-09-15
致终将努力的我们 2019-12-02