user1243746
user1243746

Reputation:

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

I have the in-memory representation of a rune

key := make([]byte, 4)

Now, how to convert it to a rune?

Upvotes: 4

Views: 19108

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382454

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)

Upvotes: 11

Related Questions