How to write Raku's trans routine/operator in Go
I was looking for a way to transliterate(translate) English numbers to Persian numbers in Go. Such functionality is usually found in programming languages, but I wasn't expecting too much from Go.
It's very easy to do in Raku:
say 567.trans: '0'..'9' => '۰'..'۹'
=output ۵۶۷
say TR/0..9/۰..۹/ given 567
=output ۵۶۷
For Go I found xstrings module which has a
Translate
function. But the solution I came up with was using
NewReplacer
function from Go's internal strings
module:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.NewReplacer(`0`, `۰`, `1`, `۱`, `2`, `۲`, `3`, `۳`, `4`, `۴`, `5`, `۵`, `6`, `۶`, `7`, `۷`, `8`, `۸`, `9`, `۹`).Replace(`567`))
}