47

I need to convert an uint32 to string. How can I do that? strconv.Itoa doesn't seem to work.

Long story:
I need to convert an UID received through the imap package to string so that I can set it later as a sequence. As a side note I'm wondering why such conversions are difficult in Go. A cast string(t) could have been so much easier.

Nik
  • 2,885
  • 2
  • 25
  • 25
hey
  • 7,299
  • 14
  • 39
  • 57
  • itoa doesn't work with uint32 // code UIDI := imap.AsNumber(rsp.MessageInfo().UID) – hey Jul 22 '14 at 11:28

4 Answers4

87

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.

fuz
  • 88,405
  • 25
  • 200
  • 352
julienc
  • 19,087
  • 17
  • 82
  • 82
  • 9
    This solution turns out to be the faster. Therefore I would recommend it to be used. `BenchmarkUintStrconv-8 50000000 36.8 ns/op` vs. `BenchmarkUintSprint-8 20000000 118 ns/op` – xsigndll Jan 06 '19 at 10:27
67

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.

creack
  • 116,210
  • 12
  • 97
  • 73
6

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

  1. Use fmt.Sprint
  2. 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

Nik
  • 2,885
  • 2
  • 25
  • 25
1

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

Zombo
  • 1
  • 62
  • 391
  • 407