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
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM