On 6 March 2013 07:26, rocky <
rocky.b...@gmail.com> wrote:
> As my first go project, I'm just porting some code I've written in other
> languages which arranges an array nicely formatted into columns. See
>
https://code.google.com/p/go-columnize/
>
> It works as is, but instead of passing list of strings, I'd like to pass a
> slice of anything and have the routine call fmt.Sprint to turn that into a
> list of strings. How do I do this?
>
> As a very naive first attempt, I tried:
>
> import "fmt"
> func print_array(a[] interface{}) {
> for i:=0 ; i<len(a); i++ {
> fmt.Println(a[i])
> }
> }
>
> c := [] int{1,2,3}
> print_array(c)
>
> But this gives a type mismatch.
Because a []int can't be assigned to a []interface{}.
[Suppose it could. Consider:
var spoo []interface{} = []int{1,2,17}
spoo[1] = "BOOM"
Oops! we have assigned a string into an int slice. That
can't be good. Rather than imposing run-time checks
on every assignment into an element of a []interface{},
and other like situations, we simply forbid it from
happening with a static type check.
"They have different stoage representations" is true
but is more of a permitted consequence rather than
being the underlying reason.
]
>
> I then look at fmt.print.go and see what is used there is p.doPrintf which
> has signature:
>
> func (p *pp) doPrintf(format string, a []interface{})
>
> I was hoping to use the existing structure there, but things like newPrinter
> and pp are private.
>
> Suggestions? Thanks.
Copy the []int into a new []interface{}.
Chris
--
Chris "DELIBERATELY not mentioning reflection" Dollin