Browse Source

add README

Tao Wen 7 years ago
parent
commit
58ce5d9ea2
3 changed files with 55 additions and 1 deletions
  1. 35 1
      README.md
  2. 3 0
      reflect2.go
  3. 17 0
      type_map_test.go

+ 35 - 1
README.md

@@ -15,4 +15,38 @@ reflect api that avoids runtime reflect.Value cost
 
 
 [json-iterator](https://github.com/json-iterator/go) use this package to save runtime dispatching cost.
 [json-iterator](https://github.com/json-iterator/go) use this package to save runtime dispatching cost.
 This package is designed for low level libraries to optimize reflection performance.
 This package is designed for low level libraries to optimize reflection performance.
-General application should still use reflect standard library.
+General application should still use reflect standard library.
+
+# reflect2.TypeByName
+
+```go
+// given package is github.com/your/awesome-package
+type MyStruct struct {
+	// ...
+}
+
+// will return the type
+reflect2.TypeByName("awesome-package.MyStruct")
+// however, if the type has not been used
+// it will be eliminated by compiler, so we can not get it in runtime
+```
+
+# reflect2 get/set interface{}
+
+```go
+valType := reflect2.TypeOf(1)
+i := 1
+j := 10
+valType.Set(&i, &j)
+// i will be 10
+```
+
+# reflect2 get/set unsafe.Pointer
+
+```go
+valType := reflect2.TypeOf(1)
+i := 1
+j := 10
+valType.UnsafeSet(unsfae.Pointer(&i), unsafe.Pointer(&j))
+// i will be 10
+```

+ 3 - 0
reflect2.go

@@ -213,6 +213,9 @@ func TypeOfPtr(obj interface{}) PtrType {
 }
 }
 
 
 func Type2(type1 reflect.Type) Type {
 func Type2(type1 reflect.Type) Type {
+	if type1 == nil {
+		return nil
+	}
 	return ConfigUnsafe.Type2(type1)
 	return ConfigUnsafe.Type2(type1)
 }
 }
 
 

+ 17 - 0
type_map_test.go

@@ -0,0 +1,17 @@
+package reflect2_test
+
+import (
+	"github.com/modern-go/reflect2"
+	"testing"
+)
+
+type MyStruct struct {
+}
+
+func TestTypeByName(t *testing.T) {
+	typByPtr := reflect2.TypeOfPtr((*MyStruct)(nil)).Elem()
+	typByName := reflect2.TypeByName("reflect2_test.MyStruct")
+	if typByName != typByPtr {
+		t.Fail()
+	}
+}