Table of Contents
Section 1: Introduction to GoLang and Strings
1.1 Brief Overview of GoLang
GoLang, also known as Go, is an open-source programming language developed by Google. It was created by Robert Griesemer, Rob Pike, and Ken Thompson with the goal of addressing some of the shortcomings of other languages while maintaining simplicity and efficiency.

Go is designed for concurrent programming and has excellent support for multi-threading, making it well-suited for modern web development, networking, and system programming tasks.
Some key features of GoLang include:
- Static typing and garbage collection, which help ensure code safety and maintainability.
- Efficient, native execution, which provides fast performance.
- Built-in concurrency features, making it easier to handle multiple tasks simultaneously.
- A simple, clean syntax that is easy to read and understand.
1.2 What are Strings in GoLang
In GoLang, strings are sequences of characters that represent textual data. Strings are immutable, which means that once created, their contents cannot be changed. A string is essentially a slice of bytes with the added property that the bytes must be valid UTF-8 encoded Unicode code points.
Strings in GoLang can be created using double quotes, like this:
myString := "Hello, World!"
You can also create raw string literals using backticks (`), which allow you to include any character, including escape sequences, within the string:
rawString := `This is a raw string with multiple lines and escape sequences like \n are not interpreted.`
In GoLang, strings can be easily manipulated using built-in functions provided by the strings package, which offers a wide range of utilities for working with string data. Some of these utilities include string comparison, searching, and manipulation functions.
Section 2: Comparing Strings using '==' Operator
2.1 How '==' works for string comparison
In GoLang, the '==' operator is used to compare two strings for equality. It checks whether the contents of both strings are the same, character by character. If the strings have the same length and the same characters in the same order, the '==' operator returns true. Otherwise, it returns false.
2.2 Example with output and explanation
Here's an example demonstrating string comparison using the '==' operator:
package main import "fmt" func main() { string1 := "Hello, World!" string2 := "hello, world!" string3 := "Hello, World!" fmt.Println("string1 == string2:", string1 == string2) // Output: false fmt.Println("string1 == string3:", string1 == string3) // Output: true }
Output:
string1 == string2: false
string1 == string3: true
Explanation:
In this example, string1 and string2 have different characters due to the case difference, so the comparison string1 == string2 returns false. On the other hand, string1 and string3 have the same characters, so the comparison string1 == string3 returns true.
2.3 Handling input from STDIN (bufio.NewReader)
When comparing strings read from the standard input (STDIN), you should be cautious about hidden characters, such as newline characters (\n) or carriage return characters (\r), which may be included in the input. You can use the bufio.NewReader function to read input from STDIN.
Here's an example demonstrating how to read input from STDIN and compare strings using the '==' operator:
package main import ( "bufio" "fmt" "os" "strings" ) func main() { fmt.Println("Enter a string:") reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') trimmedInput := strings.TrimSpace(input) // Removing any leading/trailing whitespaces, including newline characters if trimmedInput == "GoLang" { fmt.Println("You entered the string 'GoLang'.") } else { fmt.Println("You entered a different string.") } }
Output (example interaction):
Enter a string:
GoLang
You entered the string 'GoLang'.
Enter a string:
Golang
You entered a different string.
Explanation:
In this example, we read a string from the standard input using bufio.NewReader, and then compare it with the string "GoLang" using the '==' operator. However, before performing the comparison, we remove any leading or trailing whitespaces, including newline characters, using the strings.TrimSpace function. This ensures that the comparison is accurate, even if the input string contains hidden characters.
Section 3: Trimming Strings for Accurate Comparison
3.1 How to trim newline characters and whitespaces
In GoLang, to trim newline characters and whitespaces from a string, you can use functions provided by the strings package. The strings.TrimSpace function removes any leading or trailing whitespaces, including newline characters, from a string. The strings.TrimRight function can also be used to remove specific characters, such as newline characters or carriage return characters, from the right end of a string.
3.2 Example with output and explanation
Here's an example demonstrating how to trim newline characters and whitespaces from a string:
package main import ( "fmt" "strings" ) func main() { stringWithSpaces := " GoLang " stringWithNewline := "GoLang\n" trimmedString1 := strings.TrimSpace(stringWithSpaces) trimmedString2 := strings.TrimRight(stringWithNewline, "\n") fmt.Println("Trimmed stringWithSpaces:", trimmedString1) // Output: "GoLang" fmt.Println("Trimmed stringWithNewline:", trimmedString2) // Output: "GoLang" }
Output:
Trimmed stringWithSpaces: GoLang
Trimmed stringWithNewline: GoLang
Explanation:
In this example, strings.TrimSpace is used to remove leading and trailing whitespaces from stringWithSpaces, and strings.TrimRight is used to remove the newline character from the right end of stringWithNewline. The resulting strings, trimmedString1 and trimmedString2, both contain the clean string "GoLang".
3.3 Platform-independent trimming with 'runtime.GOOS'
When handling input from different platforms, you may need to trim different newline characters. Unix-based systems use \n as the newline character, while Windows uses \r\n. To perform platform-independent trimming, you can use the runtime.GOOS constant to determine the operating system at runtime and trim the appropriate newline characters accordingly.
Here's an example demonstrating platform-independent trimming using runtime.GOOS:
package main import ( "fmt" "runtime" "strings" ) func main() { input := "GoLang\n" // Assume this string is read from STDIN and may have different newline characters if runtime.GOOS == "windows" { input = strings.TrimRight(input, "\r\n") } else { input = strings.TrimRight(input, "\n") } fmt.Println("Trimmed input:", input) // Output: "GoLang" }
Output:
Trimmed input: GoLang
Explanation:
In this example, we first check the value of runtime.GOOS to determine the operating system. If the operating system is Windows, we trim both \r and \n characters from the right end of the string using strings.TrimRight. If the operating system is not Windows, we assume it's a Unix-based system and trim only the \n character. This ensures accurate string comparison across different platforms.
Section 4: Using 'strings.Compare()' Function
4.1 Overview of 'strings.Compare()' function
The strings.Compare() function is a built-in function in Go that compares two strings lexicographically. It returns an integer result based on the lexicographical comparison:
- If the result is 0, the strings are equal.
- If the result is less than 0(a negative integer), the first string is less than the second string(comes before in lexicographical order).
- If the result is greater than 0(a positive integer), the first string is greater than the second string(comes after in lexicographical order).
4.1.1 How lexicographical comparison works?
Lexicographical comparison is a method of comparing two strings based on the alphabetical order of their characters. It is similar to how words are ordered in a dictionary. When comparing strings lexicographically, we compare the Unicode values of the characters in the strings. The comparison starts with the first character of each string and proceeds character by character until a difference is found or the end of the strings is reached.
In the above points, "less than" and "greater than" refer to the lexicographical ordering of strings. Lexicographical ordering is similar to alphabetical ordering, but considers the ordering of the individual characters based on their ASCII or Unicode values.
For example, in ASCII, the character 'A' has a decimal value of 65, while 'B' has a value of 66. So in lexicographical order, "A" is less than "B", because the ASCII value of 'A' is less than the ASCII value of 'B'.
Similarly, in the context of the strings.Compare() function, "less than" means that the first string would come before the second string in lexicographical order, while "greater than" means that the first string would come after the second string in lexicographical order.
This function can be helpful for sorting strings, but for simple equality comparison, the '==' operator is more concise and easier to read.
4.2 Examples with output and explanation
Example 1:
package main import ( "fmt" "strings" ) func main() { string1 := "GoLang" string2 := "GoLang" string3 := "golang" comparison1 := strings.Compare(string1, string2) comparison2 := strings.Compare(string1, string3) fmt.Printf("Comparison result of string1 and string2: %d\n", comparison1) // Output: Comparison result of string1 and string2: 0 fmt.Printf("Comparison result of string1 and string3: %d\n", comparison2) // Output: Comparison result of string1 and string3: 1 if comparison1 == 0 { fmt.Println("string1 equals string2") // Output: string1 equals string2 } if comparison2 != 0 { fmt.Println("string1 does not equal string3") // Output: string1 does not equal string3 } }
Output:
Comparison result of string1 and string2: 0
Comparison result of string1 and string3: -1
string1 equals string2
string1 does not equal string3
Explanation:
In this example, we use the strings.Compare() function to compare the given strings. The output indicates that string1 is equal to string2, as the comparison result is 0, and string1 is not equal to string3, as the comparison result is 1.
Example 2:
package main import ( "fmt" "strings" ) func main() { string1 := "apple" string2 := "banana" string3 := "Apple" result1 := strings.Compare(string1, string2) result2 := strings.Compare(string1, string3) result3 := strings.Compare(string1, string1) fmt.Printf("Comparing '%s' and '%s': %d\n", string1, string2, result1) fmt.Printf("Comparing '%s' and '%s': %d\n", string1, string3, result2) fmt.Printf("Comparing '%s' and '%s': %d\n", string1, string1, result3) }
Output:
Comparing 'apple' and 'banana': -1
Comparing 'apple' and 'Apple': 32
Comparing 'apple' and 'apple': 0
Explanation:
- We define string1, string2, and string3 to compare.
- We use strings.Compare() to compare the strings lexicographically.
- The output shows the result of the comparison. In this case, apple is lexicographically less than banana (result1 is -1), apple is lexicographically greater than Apple (result2 is 32), and apple is equal to itself (result3 is 0).
Section 5: Case-Insensitive String Comparison with 'strings.EqualFold()'
5.1 Overview of 'strings.EqualFold()' function
The strings.EqualFold() function is a built-in function in Go that compares two strings for equality in a case-insensitive manner. It returns a boolean value: true if the strings are equal (ignoring case differences), and false otherwise. This function is particularly useful when you want to compare strings without considering the case.
5.2 Example with output and explanation
package main import ( "fmt" "strings" ) func main() { string1 := "GoLang" string2 := "golang" isEqual := strings.EqualFold(string1, string2) fmt.Printf("Are string1 and string2 equal (case-insensitive)? %t\n", isEqual) // Output: Are string1 and string2 equal (case-insensitive)? true if isEqual { fmt.Println("string1 equals string2 (case-insensitive)") // Output: string1 equals string2 (case-insensitive) } else { fmt.Println("string1 does not equal string2 (case-insensitive)") } }
Output:
Are string1 and string2 equal (case-insensitive)? true
string1 equals string2 (case-insensitive)
Explanation:
In this example, we use the strings.EqualFold() function to compare string1 and string2 for case-insensitive equality. The output shows that the strings are equal when case differences are ignored.
5.3 Performance benchmarks
While strings.EqualFold() is a convenient way to perform case-insensitive string comparisons, its performance may vary depending on the input strings. In general, strings.EqualFold() is relatively efficient and should be suitable for most applications.
However, if performance is critical for your specific use case, it is recommended to run benchmarks with sample data to determine if strings.EqualFold() meets your requirements or if alternative methods should be considered.
For information on writing and running benchmarks in Go, you can refer to the official Go blog post on the topic: Link: https://go.dev/blog/subtests
Section 6: Custom String Comparison with 'strings.TrimFunc()'
6.1 Overview of 'strings.TrimFunc()' function
strings.TrimFunc() is a versatile function in the strings package that allows you to trim characters from the beginning and end of a string based on a custom condition. The function takes two arguments: the input string and a function that defines the trimming condition. The trimming function should have the signature func(r rune) bool, where r is a Unicode code point, and it should return true if the code point should be trimmed and false otherwise.
6.2 Example with output and explanation
Suppose we want to compare two strings, but we want to ignore any digits and special characters present at the beginning and end of the strings. We can use strings.TrimFunc() to accomplish this.
package main import ( "fmt" "strings" "unicode" ) func main() { string1 := "#$123GoLang!@" string2 := "123golang&^" trimFunc := func(r rune) bool { return !unicode.IsLetter(r) } trimmedString1 := strings.TrimFunc(string1, trimFunc) trimmedString2 := strings.TrimFunc(string2, trimFunc) fmt.Println("Trimmed String 1:", trimmedString1) fmt.Println("Trimmed String 2:", trimmedString2) equal := strings.EqualFold(trimmedString1, trimmedString2) fmt.Printf("Are the trimmed strings equal (case-insensitive)? %v\n", equal) }
Output:
Trimmed String 1: GoLang
Trimmed String 2: golang
Are the trimmed strings equal (case-insensitive)? true
Explanation:
- We define string1 and string2 with some extra characters at the beginning and end.
- We create a custom trimming function trimFunc, which returns true if the character is not a letter (i.e., it should be trimmed).
- We use strings.TrimFunc() to trim the extra characters from both strings, producing trimmedString1 and trimmedString2.
- We compare the trimmed strings using strings.EqualFold() for a case-insensitive comparison.
- The output shows that the trimmed strings are equal when ignoring the case.
Section 7: Sorting Strings with 'sort.Strings()' and 'sort.StringSlice'
7.1 Overview of 'sort.Strings()' and 'sort.StringSlice'
To sort a slice of strings in Go, you can use the 'sort.Strings()' function or the 'sort.StringSlice' type from the 'sort' package. Both methods provide a simple and convenient way to sort a collection of strings in ascending lexicographical order.
- sort.Strings(): This function takes a slice of strings as an argument and sorts it in-place.
- sort.StringSlice: This type can be used as a wrapper around a slice of strings to implement the 'sort.Interface'. It provides the 'Len()', 'Less()', and 'Swap()' methods required by the 'sort.Interface'. You can then use the 'sort.Sort()' function to sort the wrapped slice.
7.2 Example with output and explanation
package main import ( "fmt" "sort" ) func main() { words := []string{"apple", "banana", "kiwi", "orange", "grape"} // Using sort.Strings() sort.Strings(words) fmt.Println("Sorted using sort.Strings():", words) // Using sort.StringSlice stringSlice := sort.StringSlice(words) sort.Sort(stringSlice) fmt.Println("Sorted using sort.StringSlice:", stringSlice) }
Output:
Sorted using sort.Strings(): [apple banana grape kiwi orange]
Sorted using sort.StringSlice: [apple banana grape kiwi orange]
Explanation:
- We define a slice of strings called words containing various fruit names.
- We use sort.Strings() to sort the words slice in-place and print the result.
- We create a sort.StringSlice named stringSlice by wrapping the words slice. Then, we use the sort.Sort() function to sort the stringSlice. Finally, we print the sorted stringSlice.
Both methods yield the same sorted output, with the strings sorted in ascending lexicographical order.
Section 8: Best Practices for Comparing Strings in GoLang
8.1 When to use which method
Choosing the appropriate method for comparing strings in Go depends on your specific requirements. Here are some guidelines to help you make the right choice:
- '==' operator: Use the '==' operator for simple string equality checks when you are sure that the strings do not contain any hidden characters like whitespaces, newline characters, etc. This operator provides the best performance for direct string comparisons.
- Trimming strings: If you need to compare strings that might contain trailing whitespaces or newline characters, use the 'strings.TrimSpace()' or 'strings.TrimRight()' functions to remove those characters before comparing.
- 'strings.Compare()': Use 'strings.Compare()' when you need to know the lexicographical order of two strings. This function returns an integer indicating whether one string is less than, equal to, or greater than the other.
- 'strings.EqualFold()': For case-insensitive string comparisons, use the 'strings.EqualFold()' function. It provides better performance compared to converting both strings to lowercase and then using the '==' operator.
- 'strings.TrimFunc()': If you need to perform a custom string comparison that involves removing certain characters before comparing, consider using 'strings.TrimFunc()'.
Here is a flowchart showing a decision tree to help you choose the most appropriate string comparison method based on your use case.

8.2 Tips for efficient string comparison
Here are some tips for making your string comparisons more efficient in Go:
- Always choose the most appropriate method for string comparison based on your specific requirements. This will help optimize both performance and readability.
- When dealing with user input or data from external sources, it's a good idea to trim unwanted characters, such as whitespaces or newline characters, before performing string comparisons.
- If you need to perform multiple string comparisons within a loop, consider using a map with string keys instead. Maps in Go have a very efficient lookup mechanism that can significantly improve performance in such scenarios.
- When sorting strings, use the 'sort.Strings()' function or the 'sort.StringSlice' type from the 'sort' package. These methods are optimized for string sorting and provide a convenient way to sort a collection of strings.
- Avoid using the '==' operator for case-insensitive string comparisons. Instead, use 'strings.EqualFold()' for better performance.
Section 9: Conclusion
In this article, we have explored various methods for comparing strings in GoLang. Each method has its own use case, and choosing the right one depends on your specific requirements. To summarize, here are the key takeaways:
- Use the '==' operator for simple string equality checks when there are no hidden characters, like whitespaces or newline characters.
- Trim unwanted characters, such as whitespaces or newline characters, using functions like 'strings.TrimSpace()' or 'strings.TrimRight()' before performing string comparisons, especially when dealing with user input or data from external sources.
- For lexicographical string comparisons, use the 'strings.Compare()' function.
- For case-insensitive string comparisons, use the 'strings.EqualFold()' function, which provides better performance compared to converting both strings to lowercase and then using the '==' operator.
- Use 'strings.TrimFunc()' for custom string comparisons that involve removing specific characters before comparing.
- Sort strings using the 'sort.Strings()' function or the 'sort.StringSlice' type from the 'sort' package for efficient sorting of string collections.
By understanding the various string comparison methods in GoLang and their appropriate use cases, you can ensure that your code is efficient, readable, and accurate. Always choose the method that best suits your specific requirements and follow the best practices we've discussed in this article for optimal string comparison performance in Go.
I hope you found this article helpful.

Cheers!
Happy Coding.
About the Author
This article was authored by Rawnak.