问题描述:

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)

}

my output is

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

What should I be doing to interpolate a number inside a string?

网友答案:

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)
网友答案:

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

The appropriate documentation is here:

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

网友答案:

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.

Then, 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".

相关阅读:
Top