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
+8k Golang : Auto-generate reply email with text/template package
+9.5k Random number generation with crypto/rand in Go
+8.3k Android Studio : Import third-party library or package into Gradle Scripts
+6.1k Unix/Linux : Use netstat to find out IP addresses served by your website server
+13.1k Golang : Linear algebra and matrix calculation example
+17.4k Golang : Upload/Receive file progress indicator
+6k Golang : Process non-XML/JSON formatted ASCII text file example
+6.7k Golang : Pat multiplexer routing example
+25k Golang : Convert uint value to string type
+7.6k Golang : Scan files for certain pattern and rename part of the files
+10.2k Golang : Generate random integer or float number
+11.5k Golang : How to detect a server/machine network interface capabilities?