无法将 []string 转换为 []interface {}

编程入门 行业动态 更新时间:2024-10-27 14:31:18
本文介绍了无法将 []string 转换为 []interface {}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一些代码,我需要它来捕获参数并通过 fmt.Println(我想要它的默认行为,编写由空格分隔并后跟换行符的参数).但是它需要 []interface {} 但 flag.Args() 返回一个 []string.下面是代码示例:

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()...) }

这将返回以下错误:

./example.go:10: cannot use args (type []string) as type []interface {} in function argument

这是一个错误吗?fmt.Println 不应该接受 any 数组吗?顺便说一句,我也试过这样做:

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())

但我收到以下错误:

cannot convert flag.Args() (type []string) to type []interface {}

有没有Go"的方法来解决这个问题?

Is there a "Go" way to workaround this?

推荐答案

这不是错误.fmt.Println() 需要 []interface{} 类型.这意味着,它必须是 interface{} 值的切片,而不是任何切片".为了转换切片,您需要循环并复制每个元素.

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...)

不能使用任何切片的原因是 []string 和 []interface{} 之间的转换需要更改内存布局并发生在 O(n) 时间内.将类型转换为 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.

更多推荐

无法将 []string 转换为 []interface {}

本文发布于:2023-11-10 02:55:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574151.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   string   interface

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!