Go实现泛型转字符串FormatString()及性能测试

利用Go的反射,实现不同类型转字符串功能,从而实现泛型转字符串功能,并做了单元测试和性能测试。

package gotest

import (
     "encoding/json"
     "fmt"
     "reflect"
     "strconv"
     "testing"
)

func FormatString(iface interface{}) string {
     switch val := iface.(type) {
     case [] byte:
         return string(val)
    }
     v := reflect. ValueOf(iface)
     switch v. Kind() {
     case reflect.Invalid:
         return ""
     case reflect.Bool:
         return strconv. FormatBool(v. Bool())
     case reflect.String:
         return v. String()
     case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
         return strconv. FormatInt(v. Int(), 10)
     case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
         return strconv. FormatUint(v. Uint(), 10)
     case reflect.Float64:
         return strconv. FormatFloat(v. Float(), 'f', - 1, 64)
     case reflect.Float32:
         return strconv. FormatFloat(v. Float(), 'f', - 1, 32)
     case reflect.Ptr:
         b, err := json. Marshal(v. Interface())
         if err != nil {
             return "nil"
        }
         return string(b)
    }
     return fmt. Sprintf( "%v", iface)
}

func BenchmarkFormatString(b *testing.B) {
     n := 10
    b. ResetTimer()
     for i := 0; i < b.N; i++ {
         FormatString(n)
    }
}

func TestFormatString(t *testing.T) {
     n := 100.001
     s := FormatString(n)
    t. Log(s)
     if s != "100.001" {
        t. Errorf( "%s", s)
    }
}

func TestMultiFormatString(t *testing.T) {
     list := map[ string] interface{}{
         "10": 10,
         "100": "100",
         "100.001": 100.001,
         "hello": "hello",
         "[1 2 3]": [] int{ 1, 2, 3},
         "true": true,
         "map[name:jason]": map[ string] interface{}{ "name": "jason"},
    }
     for k, v := range list {
         s := FormatString(v)
        t. Log(s)
         if s != k {
            t. Errorf( "Error: %v to %s,but %s", v, k, s)
        }
    }

}


保存为formatstring_test.go

执行:
go test -v -bench=. formatstring_test.go -benchmem

结果:

	=== RUN   TestFormatString
	--- PASS: TestFormatString (0.00s)
			formatstring_test.go:60: 100.001
	=== RUN   TestMultiFormatString
	--- PASS: TestMultiFormatString (0.00s)
			formatstring_test.go:78: 100
			formatstring_test.go:78: 100.001
			formatstring_test.go:78: hello
			formatstring_test.go:78: [1 2 3]
			formatstring_test.go:78: true
			formatstring_test.go:78: map[name:jason]
			formatstring_test.go:78: 10
	goos: darwin
	goarch: amd64
	BenchmarkFormatString-8         50000000                35.8 ns/op             8 B/op          1 allocs/op
	PASS
	ok      command-line-arguments  1.838s

你可能感兴趣的:(Go)