How to convert uint32 to string?
I would simply use Sprintf or even just Sprint:
var n uint32 = 42
str := fmt.Sprint(n)
println(str)
Go is strongly typed. Casting a number directly to a string would not make sense. Think about C where string are char *
which is a pointer to the first letter of the string terminated by \0
. Casting a number to a string would result in having the first letter pointer to the address of the number, which does not make sense. This is why you need to "actively" convert.
I would do this using strconv.FormatUint
:
import "strconv"
var u uint32 = 17
var s = strconv.FormatUint(uint64(u), 10)
// "17"
Note that the expected parameter is uint64
, so you have to cast your uint32
first. There is no specific FormatUint32
function.
For a more robust solution, you can use text/template
:
package main
import (
"text/template"
"strings"
)
func format(s string, v interface{}) string {
t, b := new(template.Template), new(strings.Builder)
template.Must(t.Parse(s)).Execute(b, v)
return b.String()
}
func main() {
imap := struct{UID uint32}{999}
s := format("{{.UID}}", imap)
println(s == "999")
}
https://pkg.go.dev/text/template
To summarize:
strconv.Itoa doesn't seem to work
strconv.Itoa
accepts int
, which is signed integer (either 32 or 64 bit), architecture-dependent type (see Numeric types).
I need to convert an uint32 to string
- Use
fmt.Sprint
- Use
strconv.FormatUint
The better option is strconv.FormatUint
because it is faster, has less memory allocations (benchmark examples here or here).
A cast string(t) could have been so much easier.
Using string
does not work as some people expect, see spec:
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD".
This function is going to be removed from Go2, see Rob Pike's proposal