Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a slice of 4 bytes to a rune? In Go

Tags:

go

byte

I have the in-memory representation of a rune

key := make([]byte, 4)

Now, how to convert it to a rune?


1 Answers

There is a dedicated DecodeRune function :

func DecodeRune(p []byte) (r rune, size int)

DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes. If the encoding is invalid, it returns (RuneError, 1), an impossible result for correct UTF-8.

So you just have to import "unicode/utf8" and do

r, _ := utf8.DecodeRune(key)
like image 70
Denys Séguret Avatar answered Oct 28 '25 02:10

Denys Séguret