【发布时间】:2019-11-21 00:01:25
【问题描述】:
我正在编写一个程序,它有几个结构和函数来不同地处理这些结构。我有一个通用函数,它根据输入调用所需的函数。有没有一种通用的方法来使用 getStruct() 的返回值?
package main
var X func(s []string) A
var Y func(s []string) B
type A struct {
Name string
Place string
}
type B struct {
Name string
Place string
Value string
}
func newA(s []string) A {
a := A{
Name: s[0],
Place: s[1],
}
return a
}
func newB(s []string) B {
a := B{
Name: s[0],
Place: s[1],
Value: s[2],
}
return a
}
func getStruct(t string) interface{} {
switch {
case t == "A":
return X
case t == "B":
return Y
default:
return //someStruct
}
}
func main() {
buildNewStruct := getStruct("A") //Lets assume "A" here is got as an argument
var strSlice = []string{"Bob", "US"}
buildNewStruct(strSlice) //How to do this operation?
//I am hoping to use buildNewStruct(strSlice) to dynamically call
//either of newA(strSlice) or newB(strSlice) function
}
我曾尝试查看this 和this,后者与我的问题不完全相同。
由于我是新手,我不确定这样的事情是否可行。
【问题讨论】:
-
查看此答案的第 2 部分:stackoverflow.com/a/48492325/141555。您将执行与
getStruct基本相同的操作,但不是使用t来确定结构,而是使用interface{}中的信息,即底层type。 -
如果您的要求是,给定 len k 的切片 s,将其值应用于给定结构 S 的等效索引定位字段,那么我将使用反射。
-
@sberry 对,根据@burak,我仍然需要根据我的逻辑验证
type。我认为没有其他方法可以解决这个问题。感谢您的帮助。 -
@mh-cbon 问题是,我有许多不同的结构,具有相同数量的字段
-
@sberry,对不起,我现在明白你所说的
type是什么意思了。我的错!我想我现在可以做我想做的事了。谢谢!
标签: go