Home > Article > Backend Development > How to write a function in Golang to reverse a unicode string using only 1 assignment/operation?
php editor Zimo will take you through how to write a function in Golang to reverse a unicode string using only 1 assignment/operation. Reversing a string is a common operation, but in Golang we can achieve the effect using only 1 allocation/operation in a clever way. This method is based on the fact that strings are immutable. We can convert the string into a rune slice and then reverse the string by exchanging the elements in the slice. Next, let’s take a look at the specific implementation method!
I need to write my own reverse.Reverse
simulation for unicode strings. This is my code:
func Reverse(input string) string { runes := []rune(input) var result strings.Builder result.Grow(len(runes)) for i := len(runes) - 1; i >= 0; i-- { result.WriteRune(runes[i]) } return result.String() }
But it will result in 2 allocations/operations:
cpu: 11th Gen Intel(R) Core(TM) i7-11850H @ 2.50GHz BenchmarkReverse BenchmarkReverse-16 297900 7014 ns/op 1792 B/op 2 allocs/op
How to do only 1 allocation/operation? I know it's possible
And I don't understand why result.Grow(len(runes))
makes 5 allocations/operations and result.Grow(len(input))
- 1 allocation /Action
Create strings.Builder with the required capacity. Writes the runes from the source string to the builder in reverse order.
func Reverse(str string) string { var result strings.Builder result.Grow(len(str)) for len(str) > 0 { r, size := utf8.DecodeLastRuneInString(str) result.WriteRune(r) str = str[:len(str)-size] } return result.String() }
https://www.php.cn/link/6acfe16b984d473723a8495a84e548b7
This answer replicates the functionality in the question. I don't think it makes sense for the results to be displayed to humans as glyphs. For example, combining characters do not combine like raw strings.
Here is a contrived example that illustrates the use of the reverse function: Certain value sets of an application tend to have string keys with common prefixes and uncommon suffixes. Applications can improve the distribution of the string space by reversing the keys.
The above is the detailed content of How to write a function in Golang to reverse a unicode string using only 1 assignment/operation?. For more information, please follow other related articles on the PHP Chinese website!