輕松獲取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結構體映射出來,並把私有屬性轉化為公開屬性,那么就能輕松訪問了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM