Expanding variables and fmt.Printf() issue

72 views
Skip to first unread message

yves baumes

unread,
Jun 29, 2020, 3:22:04 AM6/29/20
to golang-nuts
Hello,

considering this code

```
package main

import (
"fmt"
)

func main() {
host := []string{"127", "0", "0", "1"}

fmt.Printf("%v.%v.%v.%v\n", host[0], host[1], host[2], host[3])
fmt.Printf("%v.%v.%v.%v\n", host[0:4]...)
}
```

The first Printf works and prints the host value.
While the second one does not compile : "./args.go:11:34: cannot use host[0:4] (type []string) as type []interface {} in argument to fmt.Printf"

If I use append() instead of Printf(), this expanding of the host variables just works out. Is this a compiler bug in the case of the fmt.Printf() ?

Regards
Yves.

Jan Mercl

unread,
Jun 29, 2020, 3:31:48 AM6/29/20
to yves baumes, golang-nuts
On Mon, Jun 29, 2020 at 9:22 AM yves baumes <yba...@gmail.com> wrote:

> If I use append() instead of Printf(), this expanding of the host variables just works out. Is this a compiler bug in the case of the fmt.Printf() ?

No bug. That's how variable arguments and assignability rules are
specified to work.

Volker Dobler

unread,
Jun 29, 2020, 6:26:01 AM6/29/20
to golang-nuts
 
If I use append() instead of Printf(), this expanding of the host variables just works out. Is this a compiler bug in the case of the fmt.Printf() ?

I doubt that
     append("%v.%v.%v.%v\n", host[0:4]...)
does compile.

V.

Marvin Renich

unread,
Jun 29, 2020, 2:10:41 PM6/29/20
to golang-nuts
* yves baumes <yba...@gmail.com> [200629 03:22]:
From the language spec at
https://golang.org/ref/spec#Passing_arguments_to_..._parameters:

If the final argument is assignable to a slice type []T, it is
passed unchanged as the value for a ...T parameter if the argument
is followed by .... In this case no new slice is created.

The final argument to Printf is []interface{}, while you are trying to
pass []string. In order for this to work, []string would have to be
assignable to []interface{}, which it isn't.

This is related to a FAQ at
https://golang.org/doc/faq#convert_slice_of_interface.

If, after reading the above links and the definition of assignability at
https://golang.org/ref/spec#Assignability, you are still unclear why it
is not compiling, ask on the list for more help.

...Marvin

Marvin Renich

unread,
Jun 29, 2020, 2:21:02 PM6/29/20
to golang-nuts
[pedantic correction]

* Marvin Renich <mr...@renich.org> [200629 14:10]:
> The final argument to Printf is []interface{}, while you are trying to
^
...interface{}

...Marvin

Reply all
Reply to author
Forward
0 new messages