Equivalent of python's encode('utf8') in golang

Jim picture Jim · Mar 1, 2017 · Viewed 7.2k times · Source

How can I convert a string in Golang to UTF-8 in the same way as one would use str.encode('utf8') in Python? (I am trying to translate some code from Python to Golang; the str comes from user input, and the encoding is used to calculate a hash)

As far as I understand, the Python code converts unicode text into a string. The string is a collection of UTF-8 bytes. This sounds similar to strings in Go. So is this encoding already done for me when I store some text as a Go string?

Should I walk over the string and try utf8.EncodeRune in go? I'm really confused.

Answer

masnun picture masnun · Mar 1, 2017

In Python, str.encode('utf8') converts a string to bytes. In Go, strings are utf-8 encoded already, if you need bytes, you can do: []byte(str).