Unable to convert [] string to [] interface {}

I am writing code and I need it to catch the arguments and pass them through fmt.Println
(I want its default behavior to write arguments separated by spaces, and then a new line). However, []interface {} is required, but flag.Args() returns a []string .
Here is a sample code:

 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 

This is mistake? Can't fmt.Println take any array ? By the way, I 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 {} 

Is there a β€œGo To” way to get around this?

+56
type-conversion go
Oct 20 '12 at 16:19
source share
2 answers

It's not a mistake. fmt.Println() requires the type []interface{} . This means that it should be a slice of interface{} values, not "any fragment". To convert a slice, you will need to iterate and copy each element.

 old := flag.Args() new := make([]interface{}, len(old)) for i, v := range old { new[i] = v } fmt.Println(new...) 

The reason you cannot use any fragment is because the conversion between []string and a []interface{} requires changing the memory layout and occurs in O (n) time. Type conversion to interface{} takes O (1) time. If they made this unnecessary for the loop, the compiler would still need to insert it.

+77
Oct 20
source share

If this is only a fragment of the lines you want to print, you can avoid the conversion and get the same result by attaching:

 package main import ( "fmt" "flag" "strings" ) func main() { flag.Parse() s := strings.Join(flag.Args(), " ") fmt.Println(s) } 
+4
Dec 19 '15 at 16:06
source share



All Articles