I'm new to Go and I'm seeing if there's a way to have a method that receives any structure as parameter.
I have something like this in my code that is a function that does exactly the same for 5 structures and returns the same structure, but I don't know if I can do that. I'm wondering if I can do something like this:
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
}
Is possible to do something like the code above? Actually what I have is something like this:
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
}
With the time this will be increasing and it will return a lot of values and I don't want a lot of return values, is there a way to do it with the first code that I posted?
You can do it the exact same way yaml.Unmarshal
does it, by taking in a value to unmarshal into:
func GetYamlData(i interface{}) {
yaml.Unmarshal(Filepath, i)
}
Example usage:
func main () {
var car Car
var motorcycle Motorcycle
var bus Bus
GetYamlData(&car)
GetYamlData(&motorcycle)
GetYamlData(&bus)
}