package main import "fmt" func reverse(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func main() { fmt.Println(reverse("Go语言")) }
The code converts the string to a rune slice to handle Unicode characters properly. It then swaps runes from start to end, reversing the string. The output is the reversed string with characters in reverse order.
package main import "fmt" func reverse(s string) string { bytes := []byte(s) for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 { bytes[i], bytes[j] = bytes[j], bytes[i] } return string(bytes) } func main() { fmt.Println(reverse("hello")) }
The code converts the string to a byte slice and swaps bytes from start to end, reversing the string. Since "hello" is ASCII, this works correctly.
package main import "fmt" func reverse(s string) string { for i := 0; i < len(s)/2; i++ { s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i] } return s } func main() { fmt.Println(reverse("hello")) }
The code tries to assign to s[i], but Go strings are immutable. This causes a compile-time error.
Unicode characters can be multiple bytes in UTF-8. Reversing bytes directly can split characters incorrectly. Using rune slices treats each character as one unit.
package main import "fmt" func reverse(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func main() { fmt.Println(reverse("Go语言123")) }
The string "Go语言123" reversed by rune slice swaps each character correctly, including multi-byte Unicode characters and ASCII digits.
