Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 836
Jim Avatar asked Mar 01 '17 20:03

Jim


1 Answers

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).

like image 52
masnun Avatar answered Oct 02 '22 16:10

masnun