Variadic Input Parameters mixed type in golang

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

Variadic Input Parameters mixed type in golang

问题

在golang中,有没有办法传递混合类型的可变输入参数?

somefunc(100, "Tom", some_dictionary, some_slice)

英文:

Is there a way to pass Variadic Input Parameters mixed type in golang ?

somefunc(100, "Tom", some_dictionary, some_slice) 

答案1

得分: 2

只需使用interface{}空接口。例如:

func somefunc(nums ...interface{}) {
	for _, j := range nums {
		fmt.Printf("%T %v\n", j, j)
	}
}

https://play.golang.org/p/gKDCJf31Fo4

英文:

Just use interface{} empty interface. As example:

func somefunc(nums ...interface{}) {
	for _, j := range nums {
		fmt.Printf("%T %v\n", j, j)
	}
}

https://play.golang.org/p/gKDCJf31Fo4

答案2

得分: 1

为了将各种数据类型传递给可变参数函数,可以将参数声明为接口类型。以下是适用于你的情况的示例代码:

package main

import "fmt"

func main() {

    some_slice := []int{1, 2, 3}
    some_dictionary := map[string]string{
        "data1": "val1",
        "data2": "val2",
    }
    someFunc(100, "Tom", some_dictionary, some_slice)
}

func someFunc(nums ...interface{}) {
    for _, v := range nums {
        fmt.Println(v)
    }
}

输出结果:

int 100
string Tom
map[string]string map[data1:val1 data2:val2]
[]int [1 2 3]

希望对你有帮助!

英文:

To accommodate various data types into variadic function make the parameter as an interface,here is a sample code for your scenario:

package main

import "fmt"

func main() {

	some_slice := []int{1, 2, 3}
	some_dictionary := map[string]string{
		"data1": "val1",
		"data2": "val2",
	}
	someFunc(100, "Tom", some_dictionary, some_slice)
}

func someFunc(nums ...interface{}) {
	for _, v := range nums {
		fmt.Println(v)
	}
}

Output:

int 100
string Tom
map[string]string map[first:a second:b]
[]string [one two]

huangapple
  • 本文由 发表于 2021年8月30日 21:11:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/68984763.html
匿名

发表评论

匿名网友

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

确定