github.com/GuanceCloud/cliutils@v1.1.21/pprofparser/tools/jsontoolkit/cast.go (about)

     1  package jsontoolkit
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  func IFaceCast2Int64(x interface{}) (int64, error) {
    10  	if x == nil {
    11  		return 0, fmt.Errorf("can not convert nil value to int64")
    12  	}
    13  
    14  	switch xx := x.(type) {
    15  	case string:
    16  		n, err := strconv.ParseInt(xx, 10, 64)
    17  		if err != nil {
    18  			return 0, fmt.Errorf("cannot convert profile.profile_start: [%s] to int64, err: %w", xx, err)
    19  		}
    20  		return n, nil
    21  
    22  	case float64:
    23  		return int64(xx), nil
    24  	case json.Number:
    25  		return xx.Int64()
    26  	case int64:
    27  		return xx, nil
    28  	case uint64:
    29  		return int64(xx), nil
    30  	case int:
    31  		return int64(xx), nil
    32  	case uint:
    33  		return int64(xx), nil
    34  	case float32:
    35  		return int64(xx), nil
    36  	}
    37  
    38  	return 0, fmt.Errorf("无法把interface{}类型: %T 转换为 int64", x)
    39  }
    40  
    41  func IFaceCast2String(x interface{}) (string, error) {
    42  	if x == nil {
    43  		return "", fmt.Errorf("can not convert nil value to string")
    44  	}
    45  
    46  	switch xx := x.(type) {
    47  	case string:
    48  		return xx, nil
    49  	case float64:
    50  		return strconv.FormatFloat(xx, 'g', -1, 64), nil
    51  	case json.Number:
    52  		return xx.String(), nil
    53  	case int64:
    54  		return strconv.FormatInt(xx, 10), nil
    55  	}
    56  
    57  	return "", fmt.Errorf("无法把interface{}类型: %T 转换为 string", x)
    58  }