Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use fmt.Sprint?

Tags:

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?

like image 939
J. Eng Avatar asked Jul 20 '17 00:07

J. Eng


People also ask

What does FMT Sprint do?

The fmt. Sprintf function in the GO programming language is a function used to return a formatted string. fmt. Sprintf supports custom format specifiers and uses a format string to generate the final output string.

What is FMT in Go language?

fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.

What verb is used for floating point number in Golang?

You can convert a number to a floating-point figure with the %f verb.


Video Answer


1 Answers

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.

like image 187
Erwin Avatar answered Oct 08 '22 17:10

Erwin