How to get all defined struct in golang?

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

package demo  type People struct{   Name string   Age uint }  type UserInfo struct{   Address string   Hobby []string   NickNage string } 

another file:

import demo 

in this file ,how to get all struct in demo pkg?

回答1:

Go retains no master list of structs, interfaces, or variables at the package level, so what you ask is unfortunately impossible.



回答2:

Drat, I was hoping that Jsor's answer was wrong, but I can't find any way to do it.

All is not lost though: If you have the source to 'demo', you could use the parser package to fish out the information you need. A bit of a hack though.



回答3:

Do you come from some scripting language? It looks so.

Go has good reasons to propagate to let not slip 'magic' into your code.

What looks easy at the beginning (have access to all structs, register them automatically somewhere, "saving" coding) will end up in debugging and maintenance nightmare when your project gets larger.

Then you will have to document and lookup all your lousy conventions and implications. I know what I am talking about, because I went this route several times with ruby and nodejs.

Instead, if you make everything explicit you get some feature, like renaming the People struct to let the compiler tell you where it is used in your whole code base (and the go compiler is faster than you).

Such possibilities are invaluable for debugging, testing and refactoring.

Also it makes your code easy to reason about for your fellow coders and yourself several months after you have written it.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!