Format a Text in Go Better Than FMT
Looking at the article title, we should clarify what we mean by better and what text formatting is. Let’s start with the former. Text formatting is an important part of programming; prepared text is used in the following tasks:
- Description/result of some operations
- Detailed log
- As a query for data selection in other systems
- And in many other fields. Better means that sf (wissance.StringFormatter) has features that fmt hasn’t (see Chapter 1 to see our text formatting approach).
1. What Can Do sf aka Wissance.stringformatter
In our earlier article, we were writing about sf convenience (convenience is a thing that is subjective to humans; here, I mean convenience based on my own background). But briefly, it is more convenient to format text like:
userNews = stringFormatter.Format(“Hi “{0}”, see latest news: {1}”, “john doe”, “1. You won 1M$ in a lottery, please give us your VISA/MS card data to receive money.”)
userNews = fmt.Sprintf(“Hi “%s”, see latest news: %s”, “john doe”, “1. You won 1M$ in a lottery, please give us your VISA/MS card data to receive money.”)
sf.FormatComplex(“Today tempearture is {temp:F4}, humidity is {hum:P100}”, map[string]any {“temp”:12.3456, “hum”:60})
func TestFormatComplexWithArgFormatting(t *testing.T) { for name, test := range map[string]struct { template string args map[string]any expected string }{ “numeric_test_1”: { template: “This is the text with an only number formatting: scientific – {mass} / {mass : e2}”, args: map[string]any{“mass”: 191.0784}, expected: “This is the text with an only number formatting: scientific – 191.0784 / 1.91e+02”, }, “numeric_test_2”: { template: “This is the text with an only number formatting: binary – {bin:B} / {bin : B8}, hexadecimal – {hex:X} / {hex : X4}”, args: map[string]any{“bin”: 15, “hex”: 250}, expected: “This is the text with an only number formatting: binary – 1111 / 00001111, hexadecimal – fa / 00fa”, }, “numeric_test_3”: { template: “This is the text with an only number formatting: decimal – {float:F} / {float : F4} / {float:F8}”, args: map[string]any{“float”: 10.5467890}, expected: “This is the text with an only number formatting: decimal – 10.546789 / 10.5468 / 10.54678900”, }, } { t.Run(name, func(t *testing.T) { assert.Equal(t, test.expected, stringFormatter.FormatComplex(test.template, test.args)) }) }
}