bekkidavis.com

Unlocking the Power of cmp.Or in Go 1.22: A Comprehensive Guide

Written on

Chapter 1: Introduction to Go 1.22 and cmp.Or

The recent Go 1.22 update, released in February 2024, introduces a variety of exciting features and enhancements to the language. A notable addition is the cmp.Or function within the standard library. This article will explore its features and provide illustrative examples of its application.

The cmp package was first integrated into the Go standard library in version 1.21, launched in August 2023. According to its documentation, this package encompasses types and functions aimed at comparing ordered values. With the 1.22 release, the cmp.Or function was added.

The signature for cmp.Or is as follows:

func Or[T comparable](vals ...T) T

The cmp.Or function accepts a variadic number of arguments of a comparable type and returns the first argument that is not equal to the zero value. If all provided arguments are zero values, it returns the zero value.

Now, let's see cmp.Or in action. Suppose we have a slice of strings, such as user inputs from questionnaires, and we need to find the first non-empty string. This seems straightforward. We could write a function that iterates over the slice and returns the first non-empty string it encounters.

However, what if the questionnaire includes integer inputs as well? That would still be manageable, wouldn't it? But what if the inputs could also be floats or even arrays of floats? Instead of creating several functions for each case, we can utilize the generic cmp.Or function to streamline our code significantly.

Another useful application of cmp.Or is when setting a fallback value for user inputs. For instance, when configuring an HTTP server, it is advisable to specify a non-zero value for parameters like ReadHeaderTimeout or ReadTimeout. If both are set to zero, it indicates that there is no timeout for reading the request, which could jeopardize your application. Setting these parameters correctly helps prevent resource exhaustion by ensuring connections that take too long to read are automatically closed.

Focusing on ReadHeaderTimeout, typically, one might define a default value in the application and use it when initializing the HTTP server. However, if the application is running in an environment with slow internet, this could lead to numerous timeouts and poor user experience. In such cases, we might want to override the default timeout value. This is where cmp.Or proves invaluable.

In the example, we first establish the default timeout value. Then, we create a helper function that determines the appropriate type for ReadHeaderTimeout based on whether the environment variable HTTP_HEADER_TIMEOUT is set. The cmp.Or function is then used to select the value: if the environment variable is set, it will be used; otherwise, the function will revert to the default value. This setup involves a few int-to-string and string-to-int conversions to ensure the values align correctly.

After running the application with go run main.go and executing a cURL request, we would see the default timeout in nanoseconds. If we set the environment variable and re-run the application, we would receive the user-defined timeout value.

To further illustrate the versatility of cmp.Or, let's examine how it can facilitate sorting a slice of structs in a customized manner. Consider a collection of books that we wish to arrange on a shelf in a specific order—first by the year of publication, then by the number of pages in case of ties, followed by the author's name alphabetically, and finally by the book title.

We can represent each book with the following struct:

type book struct {

title string

author string

year int

pages int

}

Next, we'll define a function to take a slice of books as input and return a sorted version. By creating a copy of the original data and utilizing slices.SortFunc with a custom sorting function, we can achieve our desired order. The cmp.Compare function will help us compare the values, and cmp.Or will allow us to efficiently resolve ties.

Now let's test our function with a sample set of books to confirm that the sorting works as intended.

// Sample code to demonstrate sorting

As we can see, the books are sorted correctly, with ties resolved appropriately—both "Clean Architecture" and "Designing Data-Intensive Applications" were published in 2017, but "Clean Architecture" has fewer pages, hence it appears first.

Conclusion

The cmp.Or function, while not groundbreaking within the Go ecosystem, offers a highly practical utility. It significantly reduces code complexity by streamlining the process of identifying the first non-zero value among comparable types.

Resources

  • Documentation for comparable types
  • cmp.Compare function documentation

For further understanding, check out the video "Gothic #5: Join the Sect Camp, New Camp or Old Camp?" which delves into related concepts.

Additionally, "ROBOCOP: ROGUE CITY PART 7 // The New Guy - How The Blind Guy Plays" provides insights into applying similar programming principles in a different context.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Unlocking Productivity: Mastering Keyboard Shortcuts on Windows

Discover how keyboard shortcuts on Windows can enhance your productivity and streamline your workflow.

Exploring the Journey of Julius L. Evans: A Multifaceted Career

Discover the remarkable journey of Julius L. Evans, a Navy veteran turned prolific writer and senior editor, showcasing his diverse experiences.

The Surprising Health Benefits of Matcha Tea Uncovered

Discover the remarkable health benefits of Matcha tea and how it can enhance your wellness routine.

The Uncertain Future of Flutter: Google Layoffs and Ubuntu Challenges

Analyzing the implications of Google layoffs on Flutter and Ubuntu's app development landscape.

Embracing Love in Week 15: A Journey of Gratitude and Joy

This recap highlights my commitment to spreading love through gratitude and positive actions during Week 15 of 2022.

Unlock Your Full Potential: AI Tools for Personal Growth

Explore how AI tools can significantly enhance your personal development and overall well-being.

The Unfortunate Demise of North America's Rarest Snake

An endangered snake in Florida died after a failed attempt to swallow a giant scolopendra, marking a rare and tragic event.

Mastering Programming: The Right Approach to Learning

Discover effective strategies for learning programming and avoid common pitfalls.