简体   繁体   English

存储通过反射访问的结构字段

[英]Storing field of struct accessed via reflection

I am picking up quest parameters for my game from a CSV.我正在从 CSV 中为我的游戏获取任务参数。 The parameters include a stat tracked, eg "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:条件可能类似于“Cost:4”,其中 Cost 对应于我程序内部结构中的一个字段:

type template struct {
    Cost int
    // other parameters
}

I have player stats that map card templates to the stats desired, eg我有将卡片模板映射到所需统计数据的玩家统计数据,例如

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).我知道我可以通过反映地图中每个模板的具体值并使用字段名称(“Cost”)访问所需字段来做到这一点,但这似乎非常昂贵(这是在游戏服务器上,所以必须许多玩家经常这样做)。 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.我无法将模板转换为通用 map[string]interface{},因为它在我的代码中使用,所以我需要它是强类型的。

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? TLDR:有没有办法存储对结构类型(此处为模板)的字段的引用,然后可用于从该结构的任何具体实例访问该特定字段? 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!谢谢!

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 a map[string]interface{} in the template struct to hold all the values.如果字段名称只能作为字符串提供给您,您最好为模板提供方法GetValue(name string)或其他方法,并在template结构中使用map[string]interface{}来保存所有价值观。 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?如果一方面您有一个庞大且动态的字段名称列表,那么具有静态字段名称的结构可能不是存储数据的最佳方式?

type template struct {
    data map[string]interface{}
}

func (t *template) GetValue(name string) interface{} {
   if v, ok := t.data[name]; ok {
      return v
   }
   return nil
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM