DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Java 21 Record and Pattern Matching: Master Data-Oriented Programming[Video]
  • Your Go-to Guide to Develop Cryptocurrency Blockchain in Node.Js
  • Top React Libraries for Data-Driven Dashboard App Development
  • Go Application Vulnerability Cheatsheet

Trending

  • Harnessing the Power of Observability in Kubernetes With OpenTelemetry
  • Top Secrets Management Tools for 2024
  • The Future of Kubernetes: Potential Improvements Through Generative AI
  • Deploying Heroku Apps To Staging and Production Environments With GitLab CI/CD
  1. DZone
  2. Data Engineering
  3. Data
  4. Format a Text in Go Better Than FMT

Format a Text in Go Better Than FMT

There is one more text formatting utility/lib with all FMT features, and this library processes text faster, which, in some cases, could be important.

By 
Michael Ushakov user avatar
Michael Ushakov
·
Feb. 06, 24 · Tutorial
Like (1)
Save
Tweet
Share
1.3K Views

Join the DZone community and get the full member experience.

Join For Free

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.")


Rather than:

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.")


Until version 1.2.0 sf was unable to make more precise argument formatting (i.e., use different number notation: bin, hex), starting with 1.2.0 we could do almost all that fmt supports:

  1. Bin number formatting:
    • {0:B}, 15 outputs -> 1111
    • {0:B8}, 15 outputs -> 00001111
  2. Hex number formatting
    • {0:X}, 250 outputs -> fa
    • {0:X4}, 250 outputs -> 00fa
  3. Oct number formatting
    • {0:o}, 11 outputs -> 14
  4. Float point number formatting
    • {0:E2}, 191.0478 outputs -> 1.91e+02
    • {0:F}, 10.4567890 outputs -> 10.456789
    • {0:F4}, 10.4567890 outputs -> 10.4568
    • {0:F8}, 10.4567890 outputs -> 10.45678900
  5. Percentage output
    • {0:P100}, 12 outputs -> 12%

sf has two string format methods: Format and FormatComplex. The latter also allows passing argument formatting like for Format method.

Let's consider a minimal example:

  1. We should build text using the following format "Today tempearture is {temp}, humidity is {hum} where {temp} and {hum} should be replaced with actual sensor values.
  2. We would like to specify {temp} and {hum} output, i.e., {temp} should have four digits after the dot, and {hum} must be outputted in percentages. After analyzing these requirements, we modified our template as follows: "Today tempearture is {temp:F4}, humidity is {hum:P100}".
  3. Passing 12.3456 and 60 like this:
   sf.FormatComplex("Today tempearture is {temp:F4}, humidity is {hum:P100}", map[string]any {"temp":12.3456, "hum":60})


More examples could be found in a FormatComplex unit test, see in the repository and below:

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))        })    }
}


It is clear that we've got convenient (for people with C#, Python background) library for text formatting. But we have another advantage: performance, sf makes formatting **FASTER than fmt**.

2. Performance Benefits

There is one more important thing that could distinguish a sf library: it has performance advances, both in formatting cases with argument format specifications and without them. But FormatComplex is twice faster than fmt, see picture below with the results:

sf vs fmt performance comparison

3. Conclusion

Today, we could say that there is one more text formatting utility/lib with all fmt features, and this library processes text faster, which in some cases could be important. Please give us a star on GitHub and subscribe.

GitHub Data (computing) Go (programming language)

Published at DZone with permission of Michael Ushakov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java 21 Record and Pattern Matching: Master Data-Oriented Programming[Video]
  • Your Go-to Guide to Develop Cryptocurrency Blockchain in Node.Js
  • Top React Libraries for Data-Driven Dashboard App Development
  • Go Application Vulnerability Cheatsheet

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: