英文:
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)
}
}
答案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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论