Golang : Convert(cast) string to rune and back to string example
Tutorial on how how to convert a string to rune type and back to string. Dealing with rune can be confusing sometimes because single quotes and double quotes can have different meaning in Golang. This example code below is pretty straightforward and ... is self explanatory.
Here you go!
package main
import (
"fmt"
"regexp/syntax"
)
func main() {
str := []rune("beta") // use rune slice
acharacter := rune('a') // use single quote, instead of double quote
onerune := rune('吃')
fmt.Printf("%v \n", string(str)) // convert back to string
fmt.Printf("%v \n", string(acharacter)) // convert back to string
fmt.Printf("%v \n", string(onerune)) // convert back to string
// there are times when accessing str is not acceptable because
// it is a slice. Therefore, you just have to reference the first
// element
// for example :
ok := syntax.IsWordChar(str[0]) // won't work without [0]
fmt.Printf("%v is a word ? : %v \n", string(str), ok)
}
Output :
beta
a
吃
beta is a word ? : true
See also : Golang : convert rune to integer value
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.3k Golang : Struct field tags and what is their purpose?
+4.1k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+22.3k Golang : Call function from another package
+71.7k Golang : How to convert character to ASCII and back
+11.3k Golang : Activate web camera and broadcast out base64 encoded images
+8.7k Golang : Replace a parameter's value inside a configuration file example
+9.9k Golang : Change date format to yyyy-mm-dd
+14.1k Golang : Get sub string example
+7.9k Golang : Translate language with language package example
+14.5k Golang : Check if IP address is version 4 or 6
+11.5k Elastic Search : Mapping date format and sort by date
+3.2k Golang : Get a list of crosses(instruments) available to trade from Oanda account