Given the following input:
intVal := 2612
strVal := \"2612\"
What is a mechanism for mapping to the associated unicode value as a string.
2612
is not the integer value of the unicode rune, the integer value of \u2612
is 9746
. The string "2612"
is the hex value of the rune, so parse it as a hex number and convert it to a rune
.
i, err := strconv.ParseInt(strVal, 16, 32)
if err != nil {
log.Fatal(err)
}
r := rune(i)
fmt.Println(string(r))
https://play.golang.org/p/t_e6AfbKQq
This one works:
fmt.Println("\u2612")
Because an interpreted string literal is specified in the source code, and the compiler will unquote (interpret) it. It is not the fmt package that processes this unquoting.
This doesn't work:
fmt.Println("\\u" + strVal)
Because again an interpreted string literal is used which will be resolved to a string
value \u
, and then it will be concatenated with the value of the local variable strVal
which is 2612
, so the final string
value will be \u2612
. But this is not an interpreted string literal, this is the "final" result. This won't be processed / unquoted further.
Alternatively to JimB's answer, you may also use strconv.Unquote() which does an unquoting similar to what the compiler does.
See this example:
// The original that works:
s := "\u2612"
fmt.Println(s, []byte(s))
// Using strconv.Unquote():
strVal := "2612"
s2, err := strconv.Unquote(`"\u` + strVal + `"`)
fmt.Println(s2, []byte(s2), err)
fmt.Println(s == s2)
Output (try it on the Go Playground):
☒ [226 152 146]
☒ [226 152 146] <nil>
true
Something to note here: We want to unquote the \u2612
text by strconv.Unquote()
, but Unquote()
requires that the string to be unquoted to be in quotes ("Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal..."), that's why we pre- and postpended it with a quotation mark.