Pass ... parameters to fmt.Sprintf

363 views
Skip to first unread message

Archos

unread,
Jul 3, 2010, 8:10:44 AM7/3/10
to golang-nuts
How to pass several strings to fmt.Sprintf from ... parameters?

===
package main

import (
"fmt"
)

func format(main string, block ...string) string {
a := make([]interface{}, len(block))

for i, v := range block {
a[i] = v
}

return fmt.Sprintf(main, a)
}


func main() {
s := format(`Title %s, by %s.`, "Push It", "Garbage")

fmt.Printf("%v\n", s)
}
===
Title [Push It Garbage], by %smissing.

roger peppe

unread,
Jul 3, 2010, 10:25:58 AM7/3/10
to Archos, golang-nuts
On 3 July 2010 13:10, Archos <raul...@sent.com> wrote:
> func format(main string, block ...string) string {

if you make block ...interface{}, then you can just
pass it directly to fmt.Sprintf:

return fmt.Sprintf(main, block)

otherwise you'll have to use an intermediate function
with ... interface{} parameters, assign to that and then
call Sprintf.

e.g. (untested)
func format(f string, a ...string) (r string) {
func(b ...interface{}) {
b = make([]interface{}, len(a))
for i, s := range a {
b[i] = s
}
r = fmt.Sprintf(f, b)
}()
return
}

Rob 'Commander' Pike

unread,
Jul 3, 2010, 10:54:54 AM7/3/10
to Archos, golang-nuts

You don't need to repackage them.

func format(main string, block ...string) string {

return fmt.Sprintf(main, block)
}

The repository is full of examples of things like this and there are tools to do the searching for you. In this case there's even an example in Effective Go.

-rob

Rob 'Commander' Pike

unread,
Jul 3, 2010, 10:59:10 AM7/3/10
to Rob 'Commander' Pike, Archos, golang-nuts
As rog points out, you also need to change the type of block.

-rob

Archos

unread,
Jul 3, 2010, 11:21:11 AM7/3/10
to golang-nuts

On Jul 3, 2:54 pm, "Rob 'Commander' Pike" <r...@google.com> wrote:
> On Jul 3, 2010, at 5:10 AM, Archos wrote:
> > How to pass several strings to fmt.Sprintf from ... parameters?
>
> You don't need to repackage them.
>
> func format(main string, block ...string) string {
>         return fmt.Sprintf(main, block)
>
> }
>
> The repository is full of examples of things like this and there are tools to do the searching for you.  In this case there's even an example in Effective Go.
>
That was my first try ;)

Archos

unread,
Jul 3, 2010, 11:28:21 AM7/3/10
to golang-nuts


On Jul 3, 2:25 pm, roger peppe <rogpe...@gmail.com> wrote:
It works! I was surprised that it is not what I expected in my source
code since that I was passing an []interface{} to fmt.Sprintf()
Reply all
Reply to author
Forward
0 new messages