我正在编写一些代码,我需要它来捕获参数并传递它们fmt.Println
(我希望它的默认行为,写入由空格分隔的参数,然后是换行符).但它需要[]interface {}但flag.Args()返回一个[]string.
这是代码示例:
package main
import (
"fmt"
"flag"
)
func main() {
flag.Parse()
fmt.Println(flag.Args()...)
}
Run Code Online (Sandbox Code Playgroud)
这将返回以下错误:
./example.go:10: cannot use args (type []string) as type []interface {} in function argument
Run Code Online (Sandbox Code Playgroud)
这是一个错误吗?不应该fmt.Println采取任何阵列?顺便说一句,我也试过这样做:
var args = []interface{}(flag.Args())
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
cannot convert flag.Args() (type []string) to type []interface {}
Run Code Online (Sandbox Code Playgroud)
是否有"Go"方式解决此问题?
我使用反射包来获取任意数组的类型,但得到
prog.go:17: cannot use sample_array1 (type []int) as type []interface {} in function argument [process exited with non-zero status]
Run Code Online (Sandbox Code Playgroud)
如何从数组中获取类型?我知道如何从价值中获取它.
func GetTypeArray(arr []interface{}) reflect.Type {
return reflect.TypeOf(arr[0])
}
Run Code Online (Sandbox Code Playgroud)
我刚遇到的问题是在以下情况下该怎么做:
func printItems(header string, items []interface{}, fmtString string) {
// ...
}
func main() {
var iarr = []int{1, 2, 3}
var farr = []float{1.0, 2.0, 3.0}
printItems("Integer array:", iarr, "")
printItems("Float array:", farr, "")
}
Run Code Online (Sandbox Code Playgroud)
Go没有泛型,也不允许使用集合协方差:
prog.go:26: cannot use iarr (type []int) as type []interface { } in function argument
prog.go:27: cannot use farr (type []float) as type []interface { } in function argument
Run Code Online (Sandbox Code Playgroud)
想法?
我是Go的新手,所以这可能是显而易见的.编译器不允许以下代码:(http://play.golang.org/p/3sTLguUG3l)
package main
import "fmt"
type Card string
type Hand []Card
func NewHand(cards []Card) Hand {
hand := Hand(cards)
return hand
}
func main() {
value := []string{"a", "b", "c"}
firstHand := NewHand(value)
fmt.Println(firstHand)
}
Run Code Online (Sandbox Code Playgroud)
错误是:
/tmp/sandbox089372356/main.go:15: cannot use value (type []string) as type []Card in argument to NewHand
从规范来看,它看起来像[]字符串与[]卡的底层类型不同,因此不能进行类型转换.
确实是这样,还是我错过了什么?
如果是这样的话,为什么会这样呢?假设,在一个非宠物示例程序中,我输入一个字符串片段,有没有办法将它"转换"成一片卡片,或者我是否必须创建一个新结构并将数据复制到其中?(我想避免使用,因为我需要调用的函数将修改切片内容).