Menu Close

Go – Convert byte slice into rune slice in go

Here, bytes.Runes() function is used to convert byte slice into rune slice in go. It returns slice of runes.

Runes() built-in function of bytes package interprets byte slice as a sequence of UTF-8-encoded code points and returns a slice of runes (Unicode code points) equivalent to byte slice.

bytes.Runes() function prototype:

func Runes(s []byte) []rune

Input parameters:
s: slice of bytes

Return:
It returns slice of runes equivalent to byte slice.

Explanation on convert byte slice into rune slice in go

1)
s := []byte("Hello go golang")

Output: 
U+0048 'H'
U+0065 'e'
U+006C 'l'
U+006C 'l'
U+006F 'o'
U+0020 ' '
U+0067 'g'
U+006F 'o'
U+0020 ' '
U+0067 'g'
U+006F 'o'
U+006C 'l'
U+0061 'a'
U+006E 'n'
U+0067 'g'

Example:

Code 1:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte("Hello go golang")
    
    rs := bytes.Runes(s)
    
	for _, r := range rs {
		fmt.Printf("%#U\n", r)
	}
    
}

Output:

U+0048 'H'
U+0065 'e'
U+006C 'l'
U+006C 'l'
U+006F 'o'
U+0020 ' '
U+0067 'g'
U+006F 'o'
U+0020 ' '
U+0067 'g'
U+006F 'o'
U+006C 'l'
U+0061 'a'
U+006E 'n'
U+0067 'g'

Code 2:

package main

import (
	"bytes"
	"fmt"
)

// main function
func main() {
    
    s := []byte{10, 20, 30, 40}
    
    rs := bytes.Runes(s)
    
	for _, r := range rs {
		fmt.Printf("%#U\n", r)
	}
    
}

Output:

U+000A
U+0014
U+001E
U+0028 '('

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *