fmt.Printf with []string

3,638 views
Skip to first unread message

TR NS

unread,
Aug 5, 2013, 2:06:48 PM8/5/13
to golan...@googlegroups.com
How does one pass an array of string as arguments to fmt.Printf?

    var foo = []string{"A", "B", "C"}

    fmt.Printf("%s %s %s", foo)  => "A B C"

Doesn't work b/c foo is passed as a single argument. How do I "splat" it?

Ian Lance Taylor

unread,
Aug 6, 2013, 1:12:13 AM8/6/13
to TR NS, golang-nuts
If you make foo be a []interface{} instead, you can write
fmt.Printf("%s %s %s", foo...)
Or you can simply write
fmt.Printf("%v", foo)

Ian

TR NS

unread,
Aug 6, 2013, 8:37:17 AM8/6/13
to golan...@googlegroups.com

That's what I ended up doing.

    func iface(list []string) []interface{} {
      vals := make([]interface{}, len(list))
      for i, v := range list { vals[i] = v }
      return vals
    }

    fmt.Printf("%s %s %s", iface(foo)...)

Seems crazy that I have to jump through that hoop, but alas there it is.

Thanks!

chris dollin

unread,
Aug 6, 2013, 9:00:53 AM8/6/13
to TR NS, golang-nuts
On 6 August 2013 13:37, TR NS <tran...@gmail.com> wrote:

Seems crazy that I have to jump through that hoop, but alas there it is.


Without the hoop, you could assign a non-string value into a
string slice, by assigning the string slice to an interface slice
and then assigning a non-string element to one of the interface
elements. This would be a Bad Thing if you allowed it and a
different Bad Thing if you didn't.

The craziness is less bad than either of those Bad Things.

Chris

--
Chris "method or madness, we couldn't care less" Dollin

Matthew Kane

unread,
Aug 6, 2013, 9:59:26 AM8/6/13
to chris dollin, TR NS, golang-nuts
I think it would be better if the slice you pass into a variadic function with … were immutable (or rather, mutable, but copied into a new []interface{}). Then this craziness wouldn't be necessary, and you wouldn't need to worry about assigning a non-string element to a []string.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
matt kane
twitter: the_real_mkb / nynexrepublic
http://hydrogenproject.com
Reply all
Reply to author
Forward
0 new messages