Search code examples
functiongoreturnpolymorphismreturn-value

How to return dynamic values from a function


How to implement a function like this? <What_to_use_here> ?

func callfunc(type string) <What_to_use_here> {
    if type == "string"{
        return "I am a string"
     } else if type == "integer"{
       return 1
     }
    return nil
}

type Sample struct {
   value_int int
   value_str string
}

type Sample s
s.value_int = callFunc("integer")
s.value_str = callFunc("string")

I need to assign the value coming from the callFunc to a specified type as shown. So I think returning interface will not work. Need help.


Solution

  • type Sample struct {
        value_int int
        value_str string
    }
    
    func callFunc(typ string) interface{} {
        if typ == "string" {
            return "I am a string"
        } else if typ == "integer" {
            return 1
        }
        return nil
    }
    
    func main() {
        var s Sample
        s.value_int = callFunc("integer").(int)
        s.value_str = callFunc("string").(string)
        fmt.Println(s)
    }
    

    https://play.golang.org/p/QEPVMvAhkMQ