通过反射访问结构的存储字段
我正在从CSV中拾取游戏的任务参数。这些参数包括一个跟踪的统计数据,例如“ carddeployed”,以及哪种卡的条件对于此任务有效。条件可能类似于“成本:4”,其中成本与我程序内的一个结构中的字段相对应:
type template struct {
Cost int
// other parameters
}
我有播放器统计数据,将映射卡模板映射到所需的统计信息,例如
playerStats["CardsDeployed"] = map[template]uint{}
给定任务条件,我如何过滤此地图所有符合这种情况的模板?我知道我可以通过反思地图中每个模板的具体值,并使用字段名称访问所需字段(“ COST”),但这似乎非常昂贵(这似乎非常昂贵(这是在游戏服务器上经常为许多球员完成)。我无法将模板转换为通用映射[String]接口{},因为它在整个代码中都使用,因此我需要强烈键入它。
TLDR:是否有一种方法可以存储对结构类型(此处模板)的字段的引用,然后可以使用该结构的任何具体实例访问该特定字段?我已经知道程序运行时的结构布局和所有任务,因此在这种情况下,我只需要运行一次反射并存储字段参考。
请让我知道是否有其他详细信息会有所帮助。谢谢!
I am picking up quest parameters for my game from a CSV. The parameters include a stat tracked, e.g. "CardsDeployed", and conditions for what kind of cards are valid for this quest. The condition might be something like "Cost:4" where Cost corresponds to a field in a struct inside my program:
type template struct {
Cost int
// other parameters
}
I have player stats that map card templates to the stats desired, e.g.
playerStats["CardsDeployed"] = map[template]uint{}
Given a quest condition, how do I filter this map for all templates that meet that condition? I know I can do this by reflecting on the concrete value of every template in the map, and accessing the desired field using the field name ("Cost"), but this seems very expensive (this is on the game server so has to be done frequently for many players). I cannot convert template to a generic map[string]interface{} because it is used throughout my code, and so I need it to be strongly typed.
TLDR: Is there a way to store a reference to the field of a struct type (here template) that can then be used to access that particular field from any concrete instance of that struct? I already know the struct layout and all the quests when my program runs, so in that case I only need to run the reflection once and store the field reference.
Please let me know if any further details would help. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您提到我的评论是您要“解决”问题的解决方案。我认为这应该是一个答案。因此:
如果仅作为字符串才能避免字段名称,那么您最好将模板提供方法
getValue(name string)
或其他东西,并使用map [字符串]接口{}
在模板
结构中以保持所有值。如果一端您有一个大型且动态的字段名称列表,则可能是静态字段名称的结构不是存储数据的最佳方法吗?Since you mentioned that my comment was the solution that you went for to "solve" the problem. I reckon it should perhaps be an answer. So:
In the case that the field name is avaiable to you only as a string, you may be better off giving template a method
GetValue(name string)
or something and use amap[string]interface{}
in thetemplate
struct to hold all the values. If on one end you have a large and dynamic list of field names, perhaps a struct with static field names is not the best way to store the data?