Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
Problem :
You want to print rune, unicode or CJK(Chinese/Japanese/Korean) characters with Golang, but you are getting funny result. How to print rune properly?
Solution :
Use quoted verb in your Printf statement. From https://blog.golang.org/strings :
"The %q (quoted) verb will escape any non-printable byte sequences in a string so the output is unambiguous."
For example :
package main
import (
"fmt"
)
func main() {
sr := '\u212A'
fmt.Println(sr) // wrong way to print!
fmt.Printf("%+q\n", sr) // print back the unicode
fmt.Printf("%q\n", sr) // print K (Kelvin symbol)
src := '你'
fmt.Printf("%q\n", src) // print character 你
fmt.Printf("%+q\n", src) // print unicode codepoint
}
Output :
8490
'\u212a'
'K'
'你'
'\u4f60'
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.3k Useful methods to access blocked websites
+22.2k Golang : Print out struct values in string format
+9.1k Golang : Wait and sync.WaitGroup example
+6.1k Golang : Squaring elements in array
+10.7k Golang : md5 hash of a string
+17k Golang : Iterating Elements Over A List
+4.6k Python : Print unicode escape characters and string
+11.7k Golang : Convert(cast) uintptr to string example
+9.9k Android Studio : Create custom icons for your application example
+39.2k Golang : How to count duplicate items in slice/array?
+11.1k Golang : Display list of countries and ISO codes
+22.1k Golang : Fix type interface{} has no field or no methods and type assertions example