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
+10.1k Golang : Turn string or text file into slice example
+7.1k Nginx : Password protect a directory/folder
+10.7k Golang : Flip coin example
+9.3k Golang : does not implement flag.Value (missing Set method)
+20.4k Golang : Reset or rewind io.Reader or io.Writer
+8.5k Golang : Convert word to its plural form example
+19.7k Golang : Close channel after ticker stopped example
+7.7k Golang : Dealing with struct's private part
+8.3k How to show different content from website server when AdBlock is detected?
+52.8k Golang : How to get struct field and value by name
+7k How to let Facebook Login button redirect to a particular URL ?
+22.1k Golang : Use TLS version 1.2 and enforce server security configuration over client