32

I am having a function like this:

package main
import "flag"
import "fmt"

func print_out_type(x anything) string {
    switch v := x.(type) {
        case string:
             return "A string"
        case int32:
             return "An Integer"
        default:
             return "A default"
    }
}

func main() {
    wordPtr := flag.String("argument1", "foo", "a String")
    numPtr := flag.Int("argument2", 42, "an Integer")
    flag.Parse()
    fmt.Println("word: ", *wordPtr)
    fmt.Println("number: ", *numPtr)
}

I am trying to return different types of strings based on the type. I am just stuck at the point of how do I write a function that accepts arguments of different types.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Muhammad Lukman Low
  • 8,177
  • 11
  • 44
  • 54

3 Answers3

58

You can use interface types as arguments, in which case you can call the function with any type that implements the given interface. In Go types automatically implement any interfaces if they have the interface's methods. So if you want to accept all possible types, you can use empty interface (interface{}) since all types implement that. No other modification needs to be done to your function.

func print_out_type(x interface{}) string {
    switch v := x.(type) {
        case string:
             return "A string"
        case int32:
             return "An Integer"
        default:
             return "A default"
    }
}

You can also use the reflect package to study the type of an interface variable. For Example:

func print_out_type(x interface{}) string {
    return reflect.TypeOf(x).String()
}

func main() {
    fmt.Println(print_out_type(42))
    fmt.Println(print_out_type("foo"))
}

Will print

int

string

Community
  • 1
  • 1
jussius
  • 3,114
  • 15
  • 21
  • 1
    How can get the value that was sent to the variable and use it in the function? I am using data := x.(ConcreteType) but this will have the scope of switch statement and I can't use it outside that scope – Sharad Aug 12 '19 at 17:18
7

Starting with Go 1.18. you can use generics to specify which types can be used in a function.

func print_out_type[T any](x T) string {
    return fmt.Sprintf("%T", x)
}

https://go.dev/doc/tutorial/generics

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Damir Luketic
  • 71
  • 1
  • 2
-5
  1. First, if you are using a type assertion, you need to check that this operation is successful. eg: value, ok := temp.(int)
  2. Second, you can use the interface{} type variable as a parameter to the function. In the Function, you can use type assertion to check the parameter's real type and print out.
Manigandan Arjunan
  • 2,260
  • 1
  • 25
  • 42
fengzixu
  • 9
  • 1