dsgsdg206050 2018-02-08 06:05
浏览 121

将基本数据类型值转换为字符串的推荐方法

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?

  • 写回答

1条回答 默认 最新

  • du548397507 2018-02-08 07:40
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog