blackminchia
blackminchia

Reputation: 19

%d golang, how do you add spaces between Prints?

I have question related to golang verbs, especially %d. In this case I have "%4d " that I can't understand how does it prints the empty space that actually reduces in size when printing bigger numbers like in the last line with 2 digit numbers (3 empty spaces) and with 1 digit numbers where it prints 4 empty spaces?

for _, line := range s {
    for _, value := range line {
        fmt.Printf("%4d ", value)
    }
    fmt.Println()
}

$ go run main.go 5
   1    2    3    4    5
   2    4    6    8   10
   3    6    9   12   15
   4    8   12   16   20
   5   10   15   20   25

Upvotes: 0

Views: 1001

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51542

As the documentation for the fmt package states:

For most values, width is the minimum number of runes to output, padding the formatted form with spaces if necessary.

In your case, it outputs a minimum of 4 runes, padding as necessary. %04d would pad with zeros.

Upvotes: 7

Related Questions