如何将任何结构作为参数发送到方法并返回该结构



我是Go的新手,我正在研究是否有一种方法可以接收任何结构作为参数。

我的代码中有这样一个函数,它对5个结构做了完全相同的操作,并返回了相同的结构,但我不知道我是否能做到这一点。我想知道我是否可以做这样的事情:

type Car struct {
Model   string `yaml:"Model"`
Color   string `yaml:"Color"`
Wheels  int    `yaml:Wheels"`
Windows int    `yaml:"Windows"` 
}
type Motorcycle struct {
Model    string `yaml:"Model"`
Color    string `yaml:"Color"`
Wheels   int      `yaml:Wheels"`
}
type Bus struct {
Model      string `yaml:"Model"`
Color      string `yaml:"Color"`
Wheels     int    `yaml:Wheels"`
Passengers int    `yaml:"Passengers"`
}
func main () {
car := GetYamlData(Car)
motorcycle := GetYamlData(Motorcycle)
Bus := GetYamlData(Bus)
}
func GetYamlData(struct anyStructure) (ReturnAnyStruct struct){
yaml.Unmarshal(yamlFile, &anyStructure)
return anyStructure
}

是否可以执行类似上面代码的操作?事实上,我有这样的东西:

func main(){
car, _, _ := GetYamlData("car")
_,motorcycle,_ := GetYamlData("motorcycle")
_,_,bus := GetYamlData("bus")
}
func GetYamlData(structureType string) (car *Car, motorcycle *Motorcycle, bus *Bus){
switch structureType{
case "car":
yaml.Unmarshal(Filepath, car)
case "motorcycle":
yaml.Unmarshal(Filepath, motorcycle)
case "bus":
yaml.Unmarshal(Filepath, bus)
}
return car, motorcycle, bus
}

随着时间的推移,它会返回很多值,我不想要很多返回值,有没有办法用我发布的第一个代码做到这一点?

您可以采用与yaml.Unmarshal完全相同的方式,通过取一个值来解组为:

func GetYamlData(i interface{}) {
yaml.Unmarshal(Filepath, i)    
}

示例用法:

func main () {
var car Car
var motorcycle Motorcycle
var bus Bus
GetYamlData(&car)
GetYamlData(&motorcycle)
GetYamlData(&bus)
}

最新更新