How to send any structure as parameter to a method and return the structure?

Hello

I’m new in GoLang and I’m seeing if there’s a way to have a method that receive any structure as parameter, I have something like this in my code that is a function that do exactly the same for 5 structures and return 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"`
}

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"`
}

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 I don’t want a lot of return values, there’s a way to do it with the first code that I posted?

Thanks!

I’s suggest something like:

func main(){
      var car Car
      var motorcycle Motorcycle
      var bus Bus
      var err error

      if err = GetYamlData("car", &car); err != nil {
           // handle err
      }
       if err = GetYamlData("motorcycle", &motorcycle); err != nil [
            // handle err
      }
       if err = GetYamlData("bus", &bus); err != nil {
            // handle err
      }
}

func GetYamlData(structType string, val interface{}) err {

     switch structureType{

            case "car":
                    return yaml.Unmarshal(Filepath, car.(*Car))
            case "motorcycle":
                    return yaml.Unmarshal(Filepath, motorcycle.(*Motorcycle))
            case "bus":
                    return yaml.Unmarshal(Filepath, bus.(*Bus))
     }

     return fmt.Errorf("unknown structType: %s", structType)
}
1 Like

I just fixed by using this:

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.