Sorry I missed yesterday. The family road trip ended later than expected, and I was too shot to write anything.
Conversions to and from a string type
…
Finally, for historical reasons, an integer value may be converted to a string type. This form of conversion yields a string containing the (possibly multi-byte) UTF-8 representation of the Unicode code point with the given integer value. Values outside the range of valid Unicode code points are converted to
"\uFFFD"
.string('a') // "a" string(65) // "A" string('\xf8') // "\u00f8" == "ø" == "\xc3\xb8" string(-1) // "\ufffd" == "\xef\xbf\xbd" type myString string myString('\u65e5') // "\u65e5" == "日" == "\xe6\x97\xa5"
The key to note here is that this says for historical reasons. In other words: You should not really do this anymore.
In fact, go vet
will fail with these types of conversions in modern versions of Go, with an error like
conversion from untyped int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)
In fact, the spec notes:
Note: This form of conversion may eventually be removed from the language. The
go vet tool
flags certain integer-to-string conversions as potential errors. Library functions such asutf8.AppendRune
orutf8.EncodeRune
should be used instead.
Exactly how they’ll remove such behavior from the language, without breaking the Go 1 compatibility promise, I don’t know… Maybe it will be removed only for modules that express a sufficiently new version of Go? We’ll see. If that ever happens.
For now, just avoid converting integers directly to strings. You’ve been warned!
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)