Tim
Tim

Reputation: 99576

What is the correct string format specifier for integer in fmt.Printf?

var count int = 5
fmt.Printf("count:%i\n", count)

Its output is

count:%!i(int=5)

What is the correct format specifier so that the output is

count:5

I look up the package fmt's method Printf in Go's package website, but it doesn't say about the syntax for a format specifier. Where can I find the syntax?

Thanks.

Upvotes: 16

Views: 49154

Answers (3)

Mayank Patel
Mayank Patel

Reputation: 8556

%d is the format specifier for integer. However, You can use %v to print the value of the variable in default format, no matter what the data type is.

For example:

package main

import (
    "fmt"
)

func main() {
    //prints Hello 1 0.5 {Hello}
    fmt.Printf("%v %v %v %v", "Hello", 1, 0.5, struct{ v string }{"Hello"})
}

Upvotes: 18

robstarbuck
robstarbuck

Reputation: 8119

You could also simply opt for the Println function:

fmt.Println("count:", count)

Upvotes: 2

evanmcdonnal
evanmcdonnal

Reputation: 48134

%d is the format specifier for base 10 integers (what you typically want) a full listing of fmt's format specifiers can be found here; https://golang.org/pkg/fmt/

var count int = 5
fmt.Printf("count:%d\n", count)
// prints count:5

Upvotes: 30

Related Questions