doutan1857 2017-07-20 00:11
浏览 855
已采纳

为什么要使用fmt.Sprint?

I really don't understand the benefit of using fmt.Sprint compared to add strings together with +. Here is an example of both in use:

func main() {
    myString := fmt.Sprint("Hello", "world")
    fmt.Println(myString)
}

and

func main() {
    myString := "Hello " + "World"
    fmt.Println(myString)
}

What is the differences and benefits of each?

  • 写回答

4条回答 默认 最新

  • dongyan1491 2017-07-20 00:43
    关注

    In your example there are no real differences as you are Sprintf to simply concaternate strings. That is indeed something which can be solved more easily by using the '+' operator.

    Take the following example, where you want to print a clear error message like "Product with ID '42' could not be found.". How does that look with your bottom approach?

    productID := 42;
    myString := "Product with ID '" + productID + "' could not be found."
    

    This would give an error (mismatched types string and int), because Go does not have support for concatenate different types together.

    So you would have to transform the type to a string first.

    productID := 42
    myString := "Product with ID '" + strconv.Itoa(productID) + "' could not be found."
    

    And, this you would have to do for every single data type other than strings.

    The fmt package in Go and similar formatting packages in almost any other language solve this by helping you with the conversions and keeping your strings clear of mass '+' operators.

    Here is how the example would look like using fmt

    product := 42
    myString := fmt.Sprintf("Product with ID '%d' could not be found.", product)
    

    Here %d is the formatting verb for 'print the argument as a number'. See https://golang.org/pkg/fmt/#hdr-Printing the various other ways of printing other types.

    Compared to concatenating fmt allows you to write your strings in a clear way, separating the template/text from the variables. And, it simplifies printing data types other than strings a lot.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)