Golang bytes.Map() function example

package bytes

Map returns a copy of the input byte slice with all its characters modified according to the mapping function. If mapping returns a negative value, the character is dropped from the string with no replacement. The characters in the input slice and the output are interpreted as UTF-8-encoded Unicode code points.

Golang bytes.Map() function usage example

 package main

 import (
 "bytes"
 "fmt"
 )

 func main() {
 str := []byte("abcxefg")

 mapping := func(replacekey rune) rune {
 if replacekey == 'x' {
 return 'd'
 }
 return replacekey
 }

 fmt.Println(string(str))

 // now replace x with d

 fmt.Println(string(bytes.Map(mapping, str)))

 }

Output :

abcxefg

abcdefg

Reference :

http://golang.org/pkg/bytes/#Map

Advertisement