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

为什么要使用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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据