https://github.com/joway/gobber
A Golang helper to access private struct field.
https://github.com/joway/gobber
Last synced: about 1 year ago
JSON representation
A Golang helper to access private struct field.
- Host: GitHub
- URL: https://github.com/joway/gobber
- Owner: joway
- Created: 2021-03-31T11:03:22.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2021-03-31T11:35:42.000Z (about 5 years ago)
- Last Synced: 2025-01-25T00:37:25.364Z (over 1 year ago)
- Language: Go
- Size: 4.88 KB
- Stars: 3
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Gobber
A Golang helper to access private struct field.
## Usage
```go
type Car struct {
name string
}
//init
gobber := gobber.New(Car{}) //Car{} just for gobber to setup struct metadata
//set private field
target := &Car{name: "old"}
ok := gobber.Set(target, "name", "new")
//get private field
namePtr := gobber.Get(target, "name")
name := *(*string)(namePtr) //"new"
```
## How it works
```text
(address of the object) + (offset of the field in struct) == (address of the field)
//Get
*(*Type)(address of the field)
//Set
*(*Type)(address of the field) = *(*Type)(address of the new value)
```
## Benchmark
```
BenchmarkDirectlyGet-8 1000000000 0.286 ns/op
BenchmarkGobberGet-8 100000000 10.2 ns/op
BenchmarkDirectlySet-8 1000000000 0.285 ns/op
BenchmarkGobberSet-8 19638064 57.3 ns/op
```