Skip to content

podhmo/snatch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

snatch

replace struct's field value

What is this?

Unsafe struct's field replacer. ⚠️ Don't use this package in production.

Install

$ go get github.com/podhmo/snatch

Usecases

  • debugging
  • testing

How to use

Use Field() or FieldOrPanic() method.

package main

import (
	"fmt"
	"unsafe"

	"github.com/podhmo/snatch"
	"github.com/podhmo/snatch/examples/00readme/program"
)

func main() {
	prog := program.New()
	prog.Run()

	fmt.Println("----------------------------------------")
	snatch.FieldOrPanic(prog, "debug", func(ptr unsafe.Pointer) {
		realPtr := (*bool)(ptr)
		*realPtr = true
	})
	prog.Run()
}

Execution result.

Run, debug= false
----------------------------------------
Run, debug= true

Then, program package's code is here.

package program

import "fmt"

// Program ...
type Program struct {
	debug bool
}

func (p *Program) Run() {
	fmt.Println("Run, debug=", p.debug)
}

func New() *Program {
	return &Program{}
}

About

replace struct's field value

Resources

License

Stars

Watchers

Forks

Packages

No packages published