https://github.com/xaionaro-go/unsafetools
Access to private/unexported fields of a structure
https://github.com/xaionaro-go/unsafetools
access golang modify private reflect struct unexported unsafe
Last synced: 4 months ago
JSON representation
Access to private/unexported fields of a structure
- Host: GitHub
- URL: https://github.com/xaionaro-go/unsafetools
- Owner: xaionaro-go
- License: cc0-1.0
- Created: 2019-09-04T19:40:41.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2024-10-24T01:43:11.000Z (over 1 year ago)
- Last Synced: 2025-11-17T14:42:05.068Z (6 months ago)
- Topics: access, golang, modify, private, reflect, struct, unexported, unsafe
- Language: Go
- Homepage:
- Size: 15.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://coveralls.io/github/xaionaro-go/unsafetools?branch=master)
[](https://godoc.org/github.com/xaionaro-go/unsafetools)
[](https://goreportcard.com/report/github.com/xaionaro-go/unsafetools)
# Description
This package provides function `FieldByName` to access to any field (including private/unexported) of a structure.
# Use case
This package is supposed to be used for unit-tests only. If you think about using it in a real production then it seems it is something wrong in your program. However yes, you can use is if you want :)
[An use case example in github.com/xaionaro-go/picapi](https://github.com/xaionaro-go/picapi/blob/2ac776187b13158bca34bafe7cbff5487f478b9b/httpserver/http_server_handle_resize_test.go#L22).
# Example
`github.com/xaionaro-go/unsafetools/test/types.go`
```go
package test
type privateStruct struct {
enableBonus bool
}
type StructWithPrivate struct {
privateStruct
initialized bool
}
func (s *StructWithPrivate) HelloWorld() (result string) {
defer func() {
if s.enableBonus {
result += ` (bonus!)`
}
}()
if !s.initialized {
return ``
}
return `hello world!`
}
```
`github.com/xaionaro-go/unsafetools/unsafetools_test.go`
```go
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/xaionaro-go/unsafetools/test"
)
func TestFindByName_positive(t *testing.T) {
s := &test.StructWithPrivate{}
assert.Equal(t, ``, s.HelloWorld())
*FieldByName(s, `initialized`).(*bool) = true
assert.Equal(t, `hello world!`, s.HelloWorld())
*FieldByName(s, `initialized`).(*bool) = false
assert.Equal(t, ``, s.HelloWorld())
}
```