How to convert a rune to unicode-style-string like `\u554a` in Golang?

For example,

package main

import "fmt"

func main() {
    r := rune('啊')
    u := fmt.Sprintf("%U", r)
    fmt.Println(string(r), u)
}

Output:

啊 U+554A

package main

import "fmt"
import "strconv"

func main() {
    quoted := strconv.QuoteRuneToASCII('啊') // quoted = "'\u554a'"
    unquoted := quoted[1:len(quoted)-1]      // unquoted = "\u554a"
    fmt.Println(unquoted)
}

This outputs:

\u554a

IMHO, it should be better:

func RuneToAscii(r rune) string {
    if r < 128 {
        return string(r)
    } else {
        return "\\u" + strconv.FormatInt(int64(r), 16)
    }
}

You can use fmt.Sprintf along with %U to get the hexadecimal value:

test = fmt.Sprintf("%U", '啊')
fmt.Println("\\u" + test[2:]) // Print \u554A

Tags:

Unicode

Go