Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a function accept multiple types?

Tags:

go

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.

like image 985
Muhammad Lukman Low Avatar asked Oct 20 '16 04:10

Muhammad Lukman Low


People also ask

How many arguments can a function accept?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.

Is there any type in GO?

Go does not have the concept of a class type, therefore, you do not have objects in Go. You can refer any data type in Go as an object. There are several data types provided by Go such as int8, int16, int32, int64, float64, string, bool etc.


2 Answers

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

like image 180
jussius Avatar answered Sep 25 '22 13:09

jussius


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

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

like image 40
Damir Luketic Avatar answered Sep 23 '22 13:09

Damir Luketic