无法将[]字符串转换为[] interface {} [英] Cannot convert []string to []interface {}
问题描述
我写了一些代码,我需要它来捕获这些参数并将它们传递给 fmt.Println
(我希望它的默认值行为,写出由空格分隔的参数,然后是换行符)。然而它需要 [] interface {}
但是 flag.Args()
返回一个 []字符串
。
下面是代码示例:
I'm writing some code, and I need it to catch the arguments and pass them through fmt.Println
(I want its default behaviour, to write arguments separated by spaces and followed by a newline). However it takes []interface {}
but flag.Args()
returns a []string
.
Here's the code example:
package main
import (
"fmt"
"flag"
)
func main() {
flag.Parse()
fmt.Println(flag.Args()...)
}
返回以下错误:
This returns the following error:
./example.go:10: cannot use args (type []string) as type []interface {} in function argument
中的接口{}这是一个错误吗?不应该 fmt.Println
带任何数组?顺便说一下,我也试过这样做:
Is this a bug? Shouldn't fmt.Println
take any array? By the way, I've also tried to do this:
var args = []interface{}(flag.Args())
但我得到以下错误:
but I get the following error:
cannot convert flag.Args() (type []string) to type []interface {}
是否有一个Go方法来解决这个问题?
Is there a "Go" way to workaround this?
推荐答案
一个错误。 fmt.Println()
需要一个 []接口{}
类型。这意味着,它必须是界面{}
值的一部分,而不是任何切片。为了转换切片,您需要循环并复制每个元素。
This is not a bug. fmt.Println()
requires a []interface{}
type. That means, it must be a slice of interface{}
values and not "any slice". In order to convert the slice, you will need to loop over and copy each element.
old := flag.Args()
new := make([]interface{}, len(old))
for i, v := range old {
new[i] = v
}
fmt.Println(new...)
您无法使用任何切片的原因是在 []字符串
和 []接口{}
之间的转换需要更改内存布局,并且发生在准时。将类型转换为 interface {}
需要O(1)次。如果他们不需要这个for循环,编译器仍然需要插入它。
The reason you can't use any slice is that conversion between a []string
and a []interface{}
requires the memory layout to be changed and happens in O(n) time. Converting a type to an interface{}
requires O(1) time. If they made this for loop unnecessary, the compiler would still need to insert it.
这篇关于无法将[]字符串转换为[] interface {}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!