interface{} 型別的轉換

chaofu發表於2019-11-05

需求 型別是 interface{} , 值是 string , 但是需要轉為 int64 , 轉個型別費那麼多功夫

每個型別都需要符合才行, 不能隨便轉

paramId := mapstr.MapStr{}\
paramId.Set("id", value3)\
id, err := paramId.Int64("id")

type MapStr map[string]interface{}
// Set set a new value for the key, the old value will be replaced\
func (cli MapStr) Set(key string, value interface{}) {\
   cli[key] = value\
}

func (cli MapStr) Int64(key string) (int64, error) {
    switch t := cli[key].(type) {
    default:
        return 0, errors.New("invalid num")
    case nil:
        return 0, errors.New("invalid key(" + key + "), not found value")
    case int:
        return int64(t), nil
    case int16:
        return int64(t), nil
    case int32:
        return int64(t), nil
    case int64:
        return t, nil
    case float32:
        return int64(t), nil
    case float64:
        return int64(t), nil
    case uint:
        return int64(t), nil
    case uint16:
        return int64(t), nil
    case uint32:
        return int64(t), nil
    case uint64:
        return int64(t), nil
    case json.Number:
        num, err := t.Int64()
        return int64(num), err
    case string:
        return strconv.ParseInt(t, 10, 64)
    }
}

相關文章