如何将不同类型的参数传递给函数?

huangapple go评论75阅读模式
英文:

how to pass different types to a function

问题

我有两个golang函数,它们做完全相同的事情,一个函数以切片作为输入,另一个函数以映射作为输入。我想将它们合并为一个函数,以避免重复。

func DoSomething([]data) {
    //做一些操作。
}

func DoSomething(map[string]data) {
    //做一些操作。
}

合并后的函数可能如下所示:

func DoSomethingNew(param type) {
    //param可以是映射或切片
}

我想知道在golang中是否可以将不同类型的参数传递给同一个函数,以及如何实现。我在谷歌上搜索了一下,但没有找到相关的内容。

英文:

I have two golang functions, doing exactly same thing, one takes input a slice and the other takes a map as input. I want to combine this into one function, to avoid duplication.

func DoSomething([]data) {
//do something.
}

func DoSomething(map[string]data) {
    //do something.
}

Combined function may look like:

    func DoSomethingNew (param type) {
       //param could be map or slice
    }

I want to know if it is possible to pass different types to same function in golang and how. I googled but couldn't find anything relevant.

答案1

得分: 7

你可以使用接口来检查类型并根据类型执行相应的操作。以下是一个示例代码:

func F(data interface{}) {
    switch data.(type){
    case []int:
        fmt.Println("Slice")
        fmt.Println(data)
    case map[string]int:
        fmt.Println("Map")
        fmt.Println(data)
    }
    
    fmt.Println()
}

你可以在Go Playground上尝试运行这段代码。

英文:

You can use interfaces <kbd>Go Playground</kbd>

func F(data interface{}) {
	switch data.(type){
	case []int:
		fmt.Println(&quot;Slice&quot;)
		fmt.Println(data)
	case map[string]int:
		fmt.Println(&quot;Map&quot;)
		fmt.Println(data)
	}
	
	fmt.Println()
}

where you actually check for the type and do something based on the type.

答案2

得分: 3

有几种方法可以实现这个,但简单的方法是让DoSomethingNew接受interface{}类型。在方法内部,你可以使用类型切换或者在这种情况下只有两个选项的情况下,可能只需要一个类型断言,然后返回错误,如果两者都失败。另一种选择是将两者作为参数,并在函数内部检查nil,使用类似的if、else-if、else模式处理输入既不是你要找的类型的错误。为了使代码更安全,你可以使用比空接口更严格的接口,所有类型都实现该接口。你还可以进行一些方法链式调用,甚至可以使用类型本身作为接收类型来实现该方法。这里有一个示例,展示了一些想法:https://play.golang.org/p/_v2AyFjGzv

英文:

There are several ways you could do this, but the simple way would be to make it so DoSomethingNew accepts the interface{} type. Inside of the method you would then do a type switch or in this case with only two options, perhaps just one type assertion, followed by the other, returning error if both fail. Another option would be to have both as arguments and check for nil inside the function with a similar if, else-if, else pattern to handle the error if the input is of neither types you're looking for. To make your code more safe you could move to a more strict interface than the empty one which all types implement. You could also do some method chaining or even implement the method with using the types themselves as the receiving type. Here's an example that shows a few of the ideas; https://play.golang.org/p/_v2AyFjGzv

huangapple
  • 本文由 发表于 2015年11月26日 07:25:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/33928175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定