I needed to implement JavaScript .length in Golang, the solution was pretty fun so I will tell you how.For some strings Golang’s len function will do, e.g.
`
“Hello World!” . length
// JS 12
len
(
“Hello World!”
)
// Golang 12
`
The problems start when you include any unicode characters, e.g. `
“👍” . length
// JS 2
len
(
“👍”
)
// Golang 4
`
This is because JavaScript is implemented in UTF-16 (or UCS-2) and Golang is in UTF-8.
To convert a string to and from UTF-16 in Golang use: `
func
toUTF16
(s string )
[] uint16 {
return utf16.Encode([] rune (s))
}
func
fromUtf16
(b [] uint16 )
string {
return
string
(utf16.Decode(b))
}
`
Now len will work properly:
`
len (toUTF16( “👍” )) // 2
`More reading: