您如何使一个函数接受多种类型? [英] How do you make a function accept multiple types?

查看:44
本文介绍了您如何使一个函数接受多种类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有这样的功能:

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.

推荐答案

您可以将接口类型用作参数,在这种情况下,您可以使用实现给定接口的任何类型来调用函数.在Go语言中,如果类型具有接口的方法,则它们会自动实现任何接口.因此,如果您想接受所有可能的类型,则可以使用空接口( interface {} ),因为所有类型都可以实现该接口.无需对功能进行其他修改.

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

将打印

int

字符串

这篇关于您如何使一个函数接受多种类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆