-2

Problem

Convert a basic type value(such as int or bool) to its string representation.

Solutions

After reading the linked resources, I find that predominantly, there are 2 ways to tackle the issue:

Method 1: Using strconv package.

strconv.Itoa(10)
strconv.FormatBool(false)

Method 2: Using fmt.Sprintf() method

fmt.Sprintf("%v", 10)
fmt.Sprintf("%v", false)

I would like to know a general guideline one can follow to choose between these alternatives. A comparison (performance, both speed and memory) might also be useful in the discussion.

Readings

How to convert a bool to a string in Go?

How to convert an int value to string in Go?

Volker
  • 40,468
  • 7
  • 81
  • 87
Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71
  • @aeroke: The question provides two possible answers, and asks which is best. If that's not opinion-based, I don't know what is. – Jonathan Hall Feb 08 '18 at 08:56

1 Answers1

1

That really depends on a lot of factors.

There are much more ways, e.g. fmt.Sprintf("%d", 10) or the strconv.Append* family. While fmt.Sprintf is very flexible and readable strconv.Itoa is a convenience function and faster while the strconv.Append family produces less garbage than the others.

Instead of general rules you should focus on readability. Converting a single int to string is best done with strvonv.Itoa. But importing strconv just to use Itoa when you already have imported fmt might be overkill. If the conversion happens on a inner loop where garbage collection might be a problem you might want to use the strcnv.Append-stuff. Turning a bool into a string can be done with a if which might allow for easy localization (which none of the above solutions provide). Package strconv does not contain functions to format e.g. complex128 or pointers so you have to use package fmt.

Here is simple but wrong answer: "To convert an int into a string use strconv.Itoa because it is short, clear and fast".

It is wrong because sometimes it might be clearer to use fmt, especially if you need it anyway and smetimes the extra garbage produced by both (strvonv.Itoa and fmt.Sprintf) is too high.

If the conversion is not in an inner loop or on the critical execution path: Do whatever you feel comfortable with and produces consistent and readable code. So the answer is just opinion based.

Volker
  • 40,468
  • 7
  • 81
  • 87