英文:
Go - Passing an array to a function receiving argument list
问题
如何在Go中将数组作为interface{}参数列表传递?
func Yalla(i...interface{}) {
fmt.Println(i...)
}
func main() {
Yalla(1,2,3)
Yalla([]int{1,2,3})
}
输出结果为:
1 2 3 //好的
[1 2 3] //不好的
这样写会导致错误:
Yalla([]int{1,2,3}...)
我知道可以创建一个新的接口数组,并逐个赋值来解决这个问题,但是否有更优雅的方法来解决?
英文:
How can I pass an array as interface{} argument list in go?
func Yalla(i...interface{}) {
fmt.Println(i...)
}
func main() {
Yalla(1,2,3)
Yalla([]int{1,2,3})
}
Will output:
1 2 3 //good
[1 2 3] //bad
This:
Yalla([]int{1,2,3}...)
Will generate an error.
I know I can make a new interface array and assign the values one by one to solve this, but is there an elegant way to do it?
答案1
得分: 5
将一个整数数组转换为interface{}切片没有简洁的快捷方式。你需要编写for循环。
调用
Yalla([...]int{1,2,3}...)
无法编译,因为整数数组和interface{}切片是不同的类型。你可以使用[:]
轻松地创建一个切片:
Yalla([...]int{1,2,3}[:]...)
但这并不能解决问题,因为整数切片和interface{}切片是不同的类型如FAQ中所解释的。
你可以按照FAQ中所示的方式复制值,
Yalla([]interface{}{1,2,3}...)
或者将可变参数的类型更改为int,
func Yalla(i ...int) {
}
如果你总是传递整数的话。
英文:
There is no elegant shortcut for converting from an array of integers to a slice of interface{}. You need to write the for loop.
The call
Yalla([...]int{1,2,3}...)
does not compile because an array of integers and a slice of interface{} are different types. You can easily create a slice over the array using [:]
:
Yalla([...]int{1,2,3}[:]...)
but this does not solve the problem because a slice of integers and a slice of interface{} are different types as explained in the FAQ.
You either need to copy the values as shown in the FAQ, start with a slice of interface{}
Yalla([]interface{}{1,2,3}...)
or change the variadic argument type to int
func Yalla(i ...int) {
}
if that's what you are always passing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论