github.com/webx-top/com@v1.2.12/convert.go (about)

     1  // Copyright 2014 com authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"): you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    11  // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    12  // License for the specific language governing permissions and limitations
    13  // under the License.
    14  
    15  package com
    16  
    17  import (
    18  	"fmt"
    19  	"strconv"
    20  )
    21  
    22  // ToStr Convert any type to string.
    23  func ToStr(value interface{}, args ...int) (s string) {
    24  	switch v := value.(type) {
    25  	case bool:
    26  		s = strconv.FormatBool(v)
    27  	case float32:
    28  		a := IntArgs(args)
    29  		s = strconv.FormatFloat(float64(v), 'f', a.Get(0, -1), a.Get(1, 32))
    30  	case float64:
    31  		a := IntArgs(args)
    32  		s = strconv.FormatFloat(v, 'f', a.Get(0, -1), a.Get(1, 64))
    33  	case int:
    34  		s = strconv.FormatInt(int64(v), IntArgs(args).Get(0, 10))
    35  	case int8:
    36  		s = strconv.FormatInt(int64(v), IntArgs(args).Get(0, 10))
    37  	case int16:
    38  		s = strconv.FormatInt(int64(v), IntArgs(args).Get(0, 10))
    39  	case int32:
    40  		s = strconv.FormatInt(int64(v), IntArgs(args).Get(0, 10))
    41  	case int64:
    42  		s = strconv.FormatInt(v, IntArgs(args).Get(0, 10))
    43  	case uint:
    44  		s = strconv.FormatUint(uint64(v), IntArgs(args).Get(0, 10))
    45  	case uint8:
    46  		s = strconv.FormatUint(uint64(v), IntArgs(args).Get(0, 10))
    47  	case uint16:
    48  		s = strconv.FormatUint(uint64(v), IntArgs(args).Get(0, 10))
    49  	case uint32:
    50  		s = strconv.FormatUint(uint64(v), IntArgs(args).Get(0, 10))
    51  	case uint64:
    52  		s = strconv.FormatUint(v, IntArgs(args).Get(0, 10))
    53  	case string:
    54  		s = v
    55  	case []byte:
    56  		s = string(v)
    57  	case []rune:
    58  		s = string(v)
    59  	case nil:
    60  		return
    61  	default:
    62  		s = fmt.Sprintf("%v", v)
    63  	}
    64  	return
    65  }
    66  
    67  type IntArgs []int
    68  
    69  func (a IntArgs) Get(index int, defaults ...int) (r int) {
    70  	if index >= 0 && index < len(a) {
    71  		r = a[index]
    72  		return
    73  	}
    74  	if len(defaults) > 0 {
    75  		r = defaults[0]
    76  	}
    77  	return
    78  }