An open API service indexing awesome lists of open source software.

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

Awesome Lists containing this project

README

          

[![Coverage Status](https://coveralls.io/repos/github/xaionaro-go/unsafetools/badge.svg?branch=master)](https://coveralls.io/github/xaionaro-go/unsafetools?branch=master)
[![GoDoc](https://godoc.org/github.com/xaionaro-go/unsafetools?status.svg)](https://godoc.org/github.com/xaionaro-go/unsafetools)
[![Go Report Card](https://goreportcard.com/badge/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())
}
```