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
+5.6k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+5.3k Golang : Calculate half life decay example
+15.9k Golang : Get current time from the Internet time server(ntp) example
+30.4k Golang : How to verify uploaded file is image or allowed file types
+22.8k Golang : Round float to precision example
+18.5k Golang : Write file with io.WriteString
+18.1k Golang : Convert IPv4 address to decimal number(base 10) or integer
+15.3k Golang : Get HTTP protocol version example
+11.3k Golang : How to pipe input data to executing child process?