Za Noza
Za Noza

Reputation: 458

How I can get return value based on argument type?

When I define function

func test(a int, b int) int {
    //bla
}

I must set arguments and return value types. How I can return value based on argument type, ex

func test(argument type) type {
    //if argument type == string, must return string
    //or else if argument int, must return integer
}

Can I do this and how?

Upvotes: 1

Views: 182

Answers (2)

doron grinstein
doron grinstein

Reputation: 11

Go does not yet have generics like C# or Java. It does have an empty interface (interface{})

Here is code that I believe answers your question, if I understood it correctly:

package main

import (
  "fmt"
  "reflect"
)


type generic interface{} // you don't have to call the type generic, you can call it X

func main() {
    n := test(10) // I happen to pass an int
    fmt.Println(n)
}


func test(arg generic) generic {
   // do something with arg
   result := arg.(int) * 2
   // check that the result is the same data type as arg
   if reflect.TypeOf(arg) != reflect.TypeOf(result) {
     panic("type mismatch")
   }
   return result;
}

Upvotes: 0

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

Go lacks generics, (not going to argue this point one way or the other), you can achieve this by passing interface{} to functions and then doing a type assertion on the other side.

package main

import "fmt"

func test(t interface{}) interface{} {
    switch t.(type) {
    case string:
        return "test"
    case int:
        return 54
    }
    return ""
}

func main() {
    fmt.Printf("%#v\n", test(55))
    fmt.Printf("%#v", test("test"))
}

You will have to type assert the value you get out

v := test(55).(int)

Upvotes: 2

Related Questions