Why would you use fmt.Sprint?

fmt.Sprint is good for concatenation different types of its parameters as it uses reflection under the hood. So, if you need to concat strings - use "+", it's much faster, but if you need to contact number and your profit fmt.Sprint just like that:

message := fmt.Sprint(500, "internal server error")

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.

Tags:

Go