modern-go/reflect2

GitHub: modern-go/reflect2

reflect2 是一个通过规避 reflect.Value 运行时开销来提升反射操作性能的 Go 语言底层库。

Stars: 827 | Forks: 77

# reflect2 [![Sourcegraph](https://sourcegraph.com/github.com/modern-go/reflect2/-/badge.svg)](https://sourcegraph.com/github.com/modern-go/reflect2?badge) [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/modern-go/reflect2) [![Build Status](https://travis-ci.org/modern-go/reflect2.svg?branch=master)](https://travis-ci.org/modern-go/reflect2) [![codecov](https://codecov.io/gh/modern-go/reflect2/branch/master/graph/badge.svg)](https://codecov.io/gh/modern-go/reflect2) [![rcard](https://goreportcard.com/badge/github.com/modern-go/reflect2)](https://goreportcard.com/report/github.com/modern-go/reflect2) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://raw.githubusercontent.com/modern-go/reflect2/master/LICENSE) 避免 runtime reflect.Value 开销的 reflect api * reflect get/set interface{},带类型检查 * reflect get/set unsafe.Pointer,不带类型检查 * `reflect2.TypeByName` 的作用类似于 java 中的 `Class.forName` [json-iterator](https://github.com/json-iterator/go) 使用此包来节省 runtime 调度开销。 此包专为底层库设计,以优化反射性能。 普通应用程序仍应使用 reflect 标准库。 # reflect2.TypeByName ``` // 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 获取/设置 interface{} ``` valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` 在 get set `type` 时,请始终使用它的指针 `*type` # reflect2 获取/设置 unsafe.Pointer ``` valType := reflect2.TypeOf(1) i := 1 j := 10 valType.UnsafeSet(unsafe.Pointer(&i), unsafe.Pointer(&j)) // i will be 10 ``` 在 get set `type` 时,请始终使用它的指针 `*type` # benchmark 此包不需要 benchmark。它实际上什么都没做。 因为它只是一个薄薄的封装,用于将 go runtime 公开。 `reflect2` 和 `reflect` 都调用了相同的 由 go 语言的 `runtime` 包提供的函数。 # unsafe 安全性 与其在应用程序中使用 unsafe 将 `[]byte` 强制转换为 `sliceHeader`。 我们不如改用 reflect2。这样,如果将来 `sliceHeader` 发生变化, 只需要升级 reflect2 即可。 reflect2 尽其所能(通过测试)保持实现与 reflect 相同。
标签:EVTX分析, 日志审计