go 私有方法调用

通过 go:linkname 标签, 导出struct的私有的方法

a1/a.go

package a1

type MyStruct struct {
	a string
	b string
}

func (t *MyStruct) hello() string {
	return t.a+t.b
}

func New(a, b string) *MyStruct {
	return &MyStruct{
		a: a,
		b: b,
	}
}

main.go

package main

import (
	"fmt"
	"github.com/pubgo/gotests/testmonkey/a1"
	_ "unsafe"
)

//go:linkname hello github.com/pubgo/gotests/testmonkey/a1.(*MyStruct).hello
func hello(t *a1.MyStruct) string

func main() {
	b := a1.New("hello", "hello")
	fmt.Println(hello(b))
}

viper 私有方法调用

//go:linkname unMarshalReader github.com/spf13/viper.(*Viper).unmarshalReader
func unMarshalReader(v *viper.Viper, in io.Reader, c map[string]interface{}) error

func UnMarshal(path string) map[string]interface{} {
	dt, err := ioutil.ReadFile(path)
	xerror.Next().ExitF(err, path)

	var c = make(map[string]interface{})
	xerror.Next().ExitF(unMarshalReader(GetCfg().Viper, bytes.NewBuffer(dt), c), path)
	return c
}
posted @ 2020-12-02 13:20  白云辉  阅读(1121)  评论(0编辑  收藏  举报