The print format "%X" use String() method of struct instead of Integer, is it a bug?

package test

import (
	"fmt"
	"testing"
)

type Dimen uint32

func (d Dimen) String() string {
	return "1px"
}

func TestType(t *testing.T) {
	var d Dimen = 0xff
	fmt.Printf("%d, 0x%X, 0x%X\n", d, d, uint32(d))
}

output:

255, 0x317078, 0xFF

the result is not expected 255, 0xFF, 0xFF, I found if remove String() method, the result will be 255, 0xFF, 0xFF.
so is it a bug?

Hi @boringwork,

%X can be applied to numeric types and strings alike. For integers, %Xevaluates to their hexadecimal format, and for strings, to a “base 16, upper-case, two characters per byte” representation of the string.

(See fmt package - fmt - pkg.go.dev → Printing → String and slice of bytes.)

1 Like

I got it, Tank you

1 Like