go

Why would you use fmt.Sprint?


I really don't understand the benefit of using fmt.Sprint compared to adding 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 are the differences and benefits of each?


Solution

  • 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.