26

The following code

package main

import (
    "fmt"
)

func main() {
    fmt.Println(say(9))
}

func say(num int)(total string){
return fmt.Sprintf("There are %s reasons to code!", num)
}

Produces the following output

There are %!s(int=9) reasons to code!

My question

What should I do to interpolate a number inside a string?

ndequeker
  • 7,336
  • 6
  • 54
  • 89
Stephen Nguyen
  • 4,877
  • 5
  • 21
  • 28
  • Possible duplicate of [Golang: format a string without printing?](http://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing) – Dan Dascalescu Feb 04 '17 at 08:50

3 Answers3

43

If you want to always use the "default" representation of no matter what type, use %v as in

fmt.Sprintf("There are %v reasons to code!", num)
metakeule
  • 3,246
  • 20
  • 29
13

Try %d instead of %s. The d stands for decimal.

The appropriate documentation is here:

http://golang.org/pkg/fmt/

David Grayson
  • 71,301
  • 23
  • 136
  • 171
2

The output is saying exactly what is happening and what you need to know!
As you are trying to use a %s verb which is meant to strings the output says that:
!s(int=0) which means:

The value is not a string, but an integer.

Thus, if you want to know what to use instead take a look at the fmt package page https://golang.org/pkg/fmt/ at the "integers" table:

%b  base 2
%c  the character represented by the corresponding Unicode code point
%d  base 10
%o  base 8
%q  a single-quoted character literal safely escaped with Go syntax.
%x  base 16, with lower-case letters for a-f
%X  base 16, with upper-case letters for A-F
%U  Unicode format: U+1234; same as "U+%04X"

So you can use any of this verbs to have the output correctly represented.
Or as previous answers says, you can also use the %v verb which means:
"the value in its default format".