轻松获取golang结构体私有变量

举个例子

如果想要获取http.DefaultServeMux里面m怎么办呢?

  1. 可以通过reflect
  2. 内存对齐
type ServeMux struct {
	Mu    sync.RWMutex
	M     map[string]muxEntry
	Es    []muxEntry
	Hosts bool
}

type muxEntry struct {
	H       http.Handler
	Pattern string
}

func GetDefaultServeMux() *ServeMux {
	return (*ServeMux)(unsafe.Pointer(http.DefaultServeMux))
}

http.ServeMux结构体映射出来,并把私有属性转化为公开属性,那么就能轻松访问了

posted @ 2021-10-09 17:13  白云辉  阅读(924)  评论(0编辑  收藏  举报