英文:
GoLang: Generic In Inner Struct and Dynamic Type
问题
我想创建一个子结构体,使用泛型类型作为变量,根据情况可以是两种类型之一。我有以下解决方案:
type Resource interface {
Phone | Computer
}
type MetricData[R Resource] struct {
ResourceName string `json:"resourceName"`
Metrics []Metric[R] `json:"metrics"`
}
type Metric[R Resource] struct {
Resource R `json:"resource"`
Occurrences int `json:"occurrences"`
Change int `json:"change"`
}
然而,我在运行时不知道Resource的类型。当我创建一个新的结构体实例时,我需要提供R的类型:
model.MetricData[model.Phone]{ResourceName: resource, Metrics: tm}
有没有办法在运行时给MetricData指定类型,并通过if/else语句根据某些条件确定类型?
英文:
I want to make a child struct use a generic type as variable can be one of two types depending on the situation. I have the following solution
type Resource interface {
Phone | Computer
}
type MetricData[R Resource] struct {
ResourceName string `json:"resourceName"`
Metrics []Metric[R] `json:"metrics"`
}
type Metric[R Resource] struct {
Resource R `json:"resource"`
Occurrences int `json:"occurrences"`
Change int `json:"change"`
}
However, I won't know the type of Resource at runtime. When I create a new struct instance I need to provide the type of R
model.MetricData[model.Phone]{ResourceName: resource, Metrics: tm}
Is there a way to give MetricData the type at runtime and determine it via if/else statement depending on some condition?
答案1
得分: 2
也许这会有所帮助(playground):
func resourceType[T Resource](r T) string {
switch any(r).(type) {
case Phone:
return "phone"
case Computer:
return "computer"
default:
return ""
}
}
英文:
May be this will help (playground):
func resourceType[T Resource](r T) string {
switch any(r).(type) {
case Phone:
return "phone"
case Computer:
return "computer"
default:
return ""
}
}
答案2
得分: 0
你可以像这样修改你的结构:
type Resource interface {}
type MetricData struct {
ResourceName string `json:"resourceName"`
Metrics []Metric `json:"metrics"`
}
type Metric struct {
Resource Resource `json:"resource"`
Occurrences int `json:"occurrences"`
Change int `json:"change"`
}
现在,要知道Resource的确切类型,你可以这样做:
dummyMetric := {Resource: models.Phone{}, Occurrence: 1, Change: 1}
resourceType := ""
switch dummyMetric.Resource.(type) {
case models.Phone:
resourceType = "phone"
case models.Computer:
resourceType = "computer"
}
希望对你有所帮助!
英文:
You can modify your structures like this:
type Resource interface {}
type MetricData struct {
ResourceName string `json:"resourceName"`
Metrics []Metric `json:"metrics"`
}
type Metric struct {
Resource Resource `json:"resource"`
Occurrences int `json:"occurrences"`
Change int `json:"change"`
}
Now, to know the exact type of Resource, you can do something like this:
dummyMetric := {Resource: models.Phone{}, Occurrence: 1, Change: 1}
resourceType := ""
switch dummyMetric.Resource.(type) {
case models.Phone:
resourceType = "phone"
case models.Computer:
resourceType = "computer"
}
Hope it helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论