README.md (2524B)
1 # reflect2 2 3 [![Sourcegraph](https://sourcegraph.com/github.com/modern-go/reflect2/-/badge.svg)](https://sourcegraph.com/github.com/modern-go/reflect2?badge) 4 [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/modern-go/reflect2) 5 [![Build Status](https://travis-ci.org/modern-go/reflect2.svg?branch=master)](https://travis-ci.org/modern-go/reflect2) 6 [![codecov](https://codecov.io/gh/modern-go/reflect2/branch/master/graph/badge.svg)](https://codecov.io/gh/modern-go/reflect2) 7 [![rcard](https://goreportcard.com/badge/github.com/modern-go/reflect2)](https://goreportcard.com/report/github.com/modern-go/reflect2) 8 [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://raw.githubusercontent.com/modern-go/reflect2/master/LICENSE) 9 10 reflect api that avoids runtime reflect.Value cost 11 12 * reflect get/set interface{}, with type checking 13 * reflect get/set unsafe.Pointer, without type checking 14 * `reflect2.TypeByName` works like `Class.forName` found in java 15 16 [json-iterator](https://github.com/json-iterator/go) use this package to save runtime dispatching cost. 17 This package is designed for low level libraries to optimize reflection performance. 18 General application should still use reflect standard library. 19 20 # reflect2.TypeByName 21 22 ```go 23 // given package is github.com/your/awesome-package 24 type MyStruct struct { 25 // ... 26 } 27 28 // will return the type 29 reflect2.TypeByName("awesome-package.MyStruct") 30 // however, if the type has not been used 31 // it will be eliminated by compiler, so we can not get it in runtime 32 ``` 33 34 # reflect2 get/set interface{} 35 36 ```go 37 valType := reflect2.TypeOf(1) 38 i := 1 39 j := 10 40 valType.Set(&i, &j) 41 // i will be 10 42 ``` 43 44 to get set `type`, always use its pointer `*type` 45 46 # reflect2 get/set unsafe.Pointer 47 48 ```go 49 valType := reflect2.TypeOf(1) 50 i := 1 51 j := 10 52 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) 53 // i will be 10 54 ``` 55 56 to get set `type`, always use its pointer `*type` 57 58 # benchmark 59 60 Benchmark is not necessary for this package. It does nothing actually. 61 As it is just a thin wrapper to make go runtime public. 62 Both `reflect2` and `reflect` call same function 63 provided by `runtime` package exposed by go language. 64 65 # unsafe safety 66 67 Instead of casting `[]byte` to `sliceHeader` in your application using unsafe. 68 We can use reflect2 instead. This way, if `sliceHeader` changes in the future, 69 only reflect2 need to be upgraded. 70 71 reflect2 tries its best to keep the implementation same as reflect (by testing).